【问题标题】:PDFBox Overlapped TextPDFBox 重叠文本
【发布时间】:2017-10-31 10:46:29
【问题描述】:

我已经使用适用于 Android 的 PDFBox 库实现了一种算法来在页面上绘制文本。问题是每当我添加新页面时,文本都会重叠,如下图所示。我确定我使用的是PDPageContentStream.newLine() 方法,但结果并不如预期。 我还缺少其他东西吗?

这是我的代码 sn-p

PDPage page1 = new PDPage();
getInstance().getAnnexe().addPage(page1);
PDPageContentStream contentStream1 = new 
PDPageContentStream(getInstance().getAnnexe(), page1, true, true);
contentStream1.beginText();
contentStream1.newLineAtOffset(100F, 650F);
contentStream1.setFont(font, fontSize);
printMultipleLines(subSet, contentStream1);
contentStream1.endText();
contentStream1.close();

这就是printMultipleLines() 方法

private void printMultipleLines(ArrayList<String> lines, PDPageContentStream contentStream) {
    try {
        for (String line :
                lines) {
            if (line.length() > 110) {
                // Print line as 2 lines
                contentStream.showText(line.substring(0, 90));
                contentStream.newLine();
                contentStream.showText(line.substring(90, line.length()));
            } else
                // Print line as a whole
                contentStream.showText(line);
            // Print Carriage Return
            contentStream.newLine();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 如果您使用 newLine,则需要设置文本前导(TL 运算符)。我不知道它是否在 Android 的 PDFBox 中可用。替代方案:使用相对 y 值调用 newLineAtOffset,例如(0, -20)。
  • @TilmanHausherr 我正在使用这条线contentStream1.newLineAtOffset(100F, 650F);
  • 是的,但是对于后续行,请尝试 (0, -20)。参数在文本块内是相对

标签: android text pdf-generation pdfbox


【解决方案1】:

感谢@TilmanHausherr,问题出在 TL 运算符上。每个新创建的页面的 TL 等于零数量的用户默认单位。我只需要设置文本前导偏移量。 这是更新的代码:

PDPage page1 = new PDPage();
getInstance().getAnnexe().addPage(page1);
PDPageContentStream contentStream1 = new 
PDPageContentStream(getInstance().getAnnexe(), page1, true, true);
// Set the Text Leading (TL operator) here!!!!
contentStream1.setLeading(12);
contentStream1.beginText();
contentStream1.newLineAtOffset(100F, 650F);
contentStream1.setFont(font, fontSize);
printMultipleLines(subSet, contentStream1);
contentStream1.endText();
contentStream1.close();

感谢 @TilmanHausherr 快速准确的回答。

【讨论】:

    猜你喜欢
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多