如何使用Apache pdfbox在PDF中生成多行

2022-08-31 22:43:02

我正在使用Pdfbox使用Java生成PDF文件。问题是,当我在文档中添加长文本内容时,它无法正确显示。仅显示其中的一部分。那也是在一行中。

我希望文本多行。

我的代码如下:

PDPageContentStream pdfContent=new PDPageContentStream(pdfDocument, pdfPage, true, true);

pdfContent.beginText();
pdfContent.setFont(pdfFont, 11);
pdfContent.moveTextPositionByAmount(30,750);            
pdfContent.drawString("I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox");
pdfContent.endText();

我的输出:

This is my output file


答案 1

除了Mark的答案之外,您可能还想知道在哪里拆分长字符串。您可以使用该方法。PDFontgetStringWidth

将所有内容放在一起,您将获得类似这样的东西(根据PDFBox版本,略有不同):

PDFBox 1.8.x

PDDocument doc = null;
try
{
    doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(doc, page);

    PDFont pdfFont = PDType1Font.HELVETICA;
    float fontSize = 25;
    float leading = 1.5f * fontSize;

    PDRectangle mediabox = page.getMediaBox();
    float margin = 72;
    float width = mediabox.getWidth() - 2*margin;
    float startX = mediabox.getLowerLeftX() + margin;
    float startY = mediabox.getUpperRightY() - margin;

    String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox"; 
    List<String> lines = new ArrayList<String>();
    int lastSpace = -1;
    while (text.length() > 0)
    {
        int spaceIndex = text.indexOf(' ', lastSpace + 1);
        if (spaceIndex < 0)
            spaceIndex = text.length();
        String subString = text.substring(0, spaceIndex);
        float size = fontSize * pdfFont.getStringWidth(subString) / 1000;
        System.out.printf("'%s' - %f of %f\n", subString, size, width);
        if (size > width)
        {
            if (lastSpace < 0)
                lastSpace = spaceIndex;
            subString = text.substring(0, lastSpace);
            lines.add(subString);
            text = text.substring(lastSpace).trim();
            System.out.printf("'%s' is line\n", subString);
            lastSpace = -1;
        }
        else if (spaceIndex == text.length())
        {
            lines.add(text);
            System.out.printf("'%s' is line\n", text);
            text = "";
        }
        else
        {
            lastSpace = spaceIndex;
        }
    }
        
    contentStream.beginText();
    contentStream.setFont(pdfFont, fontSize);
    contentStream.moveTextPositionByAmount(startX, startY);            
    for (String line: lines)
    {
        contentStream.drawString(line);
        contentStream.moveTextPositionByAmount(0, -leading);
    }
    contentStream.endText(); 
    contentStream.close();

    doc.save("break-long-string.pdf");
}
finally
{
    if (doc != null)
    {
        doc.close();
    }
}

BreakLongString.java testBreakString for PDFBox 1.8.x)

PDFBox 2.0.x

PDDocument doc = null;
try
{
    doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(doc, page);

    PDFont pdfFont = PDType1Font.HELVETICA;
    float fontSize = 25;
    float leading = 1.5f * fontSize;

    PDRectangle mediabox = page.getMediaBox();
    float margin = 72;
    float width = mediabox.getWidth() - 2*margin;
    float startX = mediabox.getLowerLeftX() + margin;
    float startY = mediabox.getUpperRightY() - margin;

    String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox"; 
    List<String> lines = new ArrayList<String>();
    int lastSpace = -1;
    while (text.length() > 0)
    {
        int spaceIndex = text.indexOf(' ', lastSpace + 1);
        if (spaceIndex < 0)
            spaceIndex = text.length();
        String subString = text.substring(0, spaceIndex);
        float size = fontSize * pdfFont.getStringWidth(subString) / 1000;
        System.out.printf("'%s' - %f of %f\n", subString, size, width);
        if (size > width)
        {
            if (lastSpace < 0)
                lastSpace = spaceIndex;
            subString = text.substring(0, lastSpace);
            lines.add(subString);
            text = text.substring(lastSpace).trim();
            System.out.printf("'%s' is line\n", subString);
            lastSpace = -1;
        }
        else if (spaceIndex == text.length())
        {
            lines.add(text);
            System.out.printf("'%s' is line\n", text);
            text = "";
        }
        else
        {
            lastSpace = spaceIndex;
        }
    }

    contentStream.beginText();
    contentStream.setFont(pdfFont, fontSize);
    contentStream.newLineAtOffset(startX, startY);
    for (String line: lines)
    {
        contentStream.showText(line);
        contentStream.newLineAtOffset(0, -leading);
    }
    contentStream.endText(); 
    contentStream.close();

    doc.save(new File(RESULT_FOLDER, "break-long-string.pdf"));
}
finally
{
    if (doc != null)
    {
        doc.close();
    }
}

BreakLongString.java test testBreakString for PDFBox 2.0.x)

成果

Screenshot of the result PDF displayed in Acrobat Reader

这看起来如预期的那样。

当然,有许多改进要做,但这应该显示如何做到这一点。

添加无条件换行符

在评论中,aleskv问道:

当字符串中有\n时,是否可以添加换行符?

通过首先在“\n”个字符处拆分字符串,然后迭代拆分结果,可以很容易地将解决方案扩展到无条件中断换行符。

例如,如果代替上面的长字符串

String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox"; 

你想用嵌入的新行字符处理这个更长的字符串

String textNL = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox.\nFurthermore, I have added some newline characters to the string at which lines also shall be broken.\nIt should work alright like this...";

您可以简单地替换

String text = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox"; 
List<String> lines = new ArrayList<String>();
int lastSpace = -1;
while (text.length() > 0)
{
    [...]
}

在上面的解决方案中

String textNL = "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox.\nFurthermore, I have added some newline characters to the string at which lines also shall be broken.\nIt should work alright like this..."; 
List<String> lines = new ArrayList<String>();
for (String text : textNL.split("\n"))
{
    int lastSpace = -1;
    while (text.length() > 0)
    {
        [...]
    }
}

(来自 BreakLongString.java testBreakStringNL

结果:

Screenshot


答案 2

我知道这有点晚了,但我对mkl的解决方案有一点问题。如果最后一行只包含一个单词,您的算法会将其写入前一行。

例如:“Lorem ipsum dolor sit amet”是您的文本,它应该在“sit”之后添加换行符。

Lorem ipsum dolor sit
amet

但它是这样做的:

Lorem ipsum dolor sit amet

我想出了我自己的解决方案,我想与你分享。

/**
 * @param text The text to write on the page.
 * @param x The position on the x-axis.
 * @param y The position on the y-axis.
 * @param allowedWidth The maximum allowed width of the whole text (e.g. the width of the page - a defined margin).
 * @param page The page for the text.
 * @param contentStream The content stream to set the text properties and write the text.
 * @param font The font used to write the text.
 * @param fontSize The font size used to write the text.
 * @param lineHeight The line height of the font (typically 1.2 * fontSize or 1.5 * fontSize).
 * @throws IOException
 */
private void drawMultiLineText(String text, int x, int y, int allowedWidth, PDPage page, PDPageContentStream contentStream, PDFont font, int fontSize, int lineHeight) throws IOException {

    List<String> lines = new ArrayList<String>();

    String myLine = "";

    // get all words from the text
    // keep in mind that words are separated by spaces -> "Lorem ipsum!!!!:)" -> words are "Lorem" and "ipsum!!!!:)"
    String[] words = text.split(" ");
    for(String word : words) {

        if(!myLine.isEmpty()) {
            myLine += " ";
        }

        // test the width of the current line + the current word
        int size = (int) (fontSize * font.getStringWidth(myLine + word) / 1000);
        if(size > allowedWidth) {
            // if the line would be too long with the current word, add the line without the current word
            lines.add(myLine);

            // and start a new line with the current word
            myLine = word;
        } else {
            // if the current line + the current word would fit, add the current word to the line
            myLine += word;
        }
    }
    // add the rest to lines
    lines.add(myLine);

    for(String line : lines) {
        contentStream.beginText();
        contentStream.setFont(font, fontSize);
        contentStream.moveTextPositionByAmount(x, y);
        contentStream.drawString(line);
        contentStream.endText();

        y -= lineHeight;
    }

}

推荐