如何使用Apache pdfbox在PDF中生成多行 [英] How to generate multiple lines in PDF using Apache pdfbox

查看:1244
本文介绍了如何使用Apache pdfbox在PDF中生成多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我希望文本有多行。



我的代码是给出的下面:

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

pdfContent.beginText();
pdfContent.setFont(pdfFont,11);
pdfContent.moveTextPositionByAmount(30,750);
pdfContent.drawString(我正在尝试在文档中创建包含大量文本内容的PDF文件。我正在使用PDFBox);
pdfContent.endText();

我的输出:



解决方案

添加到Mark的答案,您可能想知道拆分长字符串的位置。您可以使用 PDFont 方法 getStringWidth



将所有内容组合在一起就可以获得类似的内容(根据PDFBox版本略有不同):



PDFBox 1.8.x



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

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

PDRectangle mediabox = page.findMediaBox();
浮动保证金= 72;
float width = mediabox.getWidth() - 2 * margin;
float startX = mediabox.getLowerLeftX()+ margin;
float startY = mediabox.getUpperRightY() - margin;

String text =我正在尝试在文档中创建包含大量文本内容的PDF文件。我正在使用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的重量为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'是line \ n,subString);
lastSpace = -1;
}
else if(spaceIndex == text.length())
{
lines.add(text);
System.out.printf('%s'是line \ n,text);
text =;
}
其他
{
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);
}
最后
{
if(doc!= null)
{
doc.close();
}
}

(测试 testBreakStringNL



结果:




I am using Pdfbox to generate PDF files using Java. The problem is that when i add long text contents in the document, it is not displayed properly. Only a part of it is displayed. That too in a single line.

I want text to be in multiple lines.

My code is given below:

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();

My output:

解决方案

Adding to the answer of Mark you might want to know where to split your long string. You can use the PDFont method getStringWidth for that.

Putting everything together you get something like this (with minor differences depending on the PDFBox version):

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.findMediaBox();
    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 test 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)

The result

This looks as expected.

Of course there are numerous improvements to make but this should show how to do it.

Adding unconditional line breaks

In a comment aleskv asked:

could you add line breaks when there are \n in the string?

One can easily extend the solution to unconditionally break at newline characters by first splitting the string at '\n' characters and then iterating over the split result.

E.g. if instead of the long string from above

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

you want to process this even longer string with embedded new line characters

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...";

you can simply replace

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)
{
    [...]
}

in the solutions above by

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)
    {
        [...]
    }
}

(from BreakLongString.java test testBreakStringNL)

The result:

这篇关于如何使用Apache pdfbox在PDF中生成多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆