Java pdfbox换行文本

Java pdfbox换行文本,java,text,pdfbox,Java,Text,Pdfbox,我正在使用具有以下代码的PDFBox: doc = new PDDocument(); page = new PDPage(); doc.addPage(page); PDFont font = PDType1Font.COURIER; pdftitle = new PDPageContentStream(doc, page); pdftitle.beginText(); pdftitle.setFont( font, 12 ); pdftitle.moveTextPositionByAmo

我正在使用具有以下代码的PDFBox:

doc = new PDDocument();
page = new PDPage();

doc.addPage(page);
PDFont font = PDType1Font.COURIER;

pdftitle = new PDPageContentStream(doc, page);
pdftitle.beginText();
pdftitle.setFont( font, 12 );
pdftitle.moveTextPositionByAmount( 40, 740 );
pdftitle.drawString("Here I insert a lot of text");
pdftitle.endText();
pdftitle.close();

有人知道如何包装文本,使其自动转到另一行吗?

我认为不可能自动包装文本。但是你可以自己包装你的文本。请参阅和。

我在pdfBOX中找到了断线问题的解决方案

通常,需要三个步骤来包装文本:

1) 将每个单词拆分为需要包装的字符串,并将其放入字符串数组中,例如字符串[]部分

2) 使用(textlength/(一行中的字符数))创建一个stringbuffer数组,例如280/70=5>>我们需要5个换行符

3) 将部件放入stringbuffer[i],直到允许一行中的最大字符数限制

4) 循环直到stringbuffer.length<换行符

方法splitString就是执行此操作的方法。 方法writeText只是将包装好的文本绘制到pdf中

这里有一个例子

import java.io.IOException;
import java.util.ArrayList;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class pdfTest{
 private ArrayList<String> arrayList;
 private PDDocument document;
 private PDFont font = PDType1Font.HELVETICA;

 pdfTest(PDDocument document, ArrayList arrayList, PDFont font) throws COSVisitorException, IOException {
    this.document = document;
    this.arrayList = arrayList;
    this.font = font;   
    writeText(document, arrayList, 30, 750, font); //method for easily drawing a text into a pdf
 } //constructor


 public void writeText(PDDocument document, ArrayList arrayList, int positionX, int positionY, PDFont font) throws IOException, COSVisitorException {
     PDPage page = new PDPage();
     document.addPage( page );

     // Start a new content stream
     PDPageContentStream contentStream = new PDPageContentStream(document, page);

     // Define a text content stream using the selected font, moving the cursor and drawing the text in arrayList
     for(int i=0;i<arrayList.size();i++) {  
         String text=(String) arrayList.get(i);
         String [] tmpText = splitString(text);
         for( int k=0;k<tmpText.length;k++) {
             contentStream.beginText();
             contentStream.setFont(font, 12);
             contentStream.moveTextPositionByAmount(positionX, positionY);
             contentStream.drawString(tmpText[k]);           
             contentStream.endText();
             positionY=positionY-20;
         }           
         contentStream.setLineWidth((float) 0.25);
     }

     // Make sure that the content stream is closed:
     contentStream.close();      
     document.save( "Test.pdf");
     document.close();
 } //main

 public static void main(String[] args) throws COSVisitorException, IOException {
     ArrayList arrayList = new ArrayList<String>();

     PDDocument document = new PDDocument();
     PDFont font = PDType1Font.HELVETICA;
     PDPage page = new PDPage();

     arrayList.add(       "12345 56789 0 aaa bbbew wel kwäer kweork merkweporkm roer wer wer e  er"
                        + "df sdmfkl  slkdfm sdkfdof sopdkfp osdkfo sädölf söldm,f sdkfpoekr re, ä"
                        + " sdfk msdlkfmsdlk fsdlkfnsdlk fnlkdn flksdnfkl sdnlkfn kln df sdmfn sn END");
     arrayList.add("this is an example");
     arrayList.add("java pdfbox stackoverflow");         

     new pdfTest(document,arrayList,font);
     System.out.println("pdf created!");
 }

 public String [] splitString(String text) {
     /* pdfBox doesnt support linebreaks. Therefore, following steps are requierd to automatically put linebreaks in the pdf
      * 1) split each word in string that has to be linefeded and put them into an array of string, e.g. String [] parts
      * 2) create an array of stringbuffer with (textlength/(number of characters in a line)), e.g. 280/70=5 >> we need 5 linebreaks!
      * 3) put the parts into the stringbuffer[i], until the limit of maximum number of characters in a line is allowed,
      * 4) loop until stringbuffer.length < linebreaks
      * 
      */
     int linebreaks=text.length()/80; //how many linebreaks do I need?  
     String [] newText = new String[linebreaks+1];       
     String tmpText = text;
     String [] parts = tmpText.split(" "); //save each word into an array-element

     //split each word in String into a an array of String text. 
     StringBuffer [] stringBuffer = new StringBuffer[linebreaks+1]; //StringBuffer is necessary because of manipulating text
     int i=0; //initialize counter 
     int totalTextLength=0;
     for(int k=0; k<linebreaks+1;k++) {
         stringBuffer[k] = new StringBuffer();
         while(true) {               
             if (i>=parts.length) break; //avoid NullPointerException
             totalTextLength=totalTextLength+parts[i].length(); //count each word in String              
             if (totalTextLength>80) break; //put each word in a stringbuffer until string length is >80
             stringBuffer[k].append(parts[i]);
             stringBuffer[k].append(" ");
             i++;
         }
         //reset counter, save linebreaked text into the array, finally convert it to a string 
         totalTextLength=0; 
         newText[k] = stringBuffer[k].toString();
     }
     return newText;
 } 

} 
import java.io.IOException;
导入java.util.ArrayList;
导入org.apache.pdfbox.exceptions.COSVisitorException;
导入org.apache.pdfbox.pdmodel.PDDocument;
导入org.apache.pdfbox.pdmodel.PDPage;
导入org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
导入org.apache.pdfbox.pdmodel.font.PDFont;
导入org.apache.pdfbox.pdmodel.font.PDType1Font;
公共类pdfTest{
私有ArrayList ArrayList;
私人文件;
私有PDFont font=PDType1Font.HELVETICA;
pdfTest(PDDocument文档、ArrayList ArrayList、PDFont字体)引发CosVisiteException、IOException{
本文件=文件;
this.arrayList=arrayList;
this.font=font;
writeText(文档,arrayList,30750,字体);//用于轻松将文本绘制成pdf的方法
}//构造函数
public void writeText(PDDocument文档、ArrayList ArrayList、int-positionX、int-positionY、PDFont字体)引发IOException、CosVisiteException{
PDPage page=新PDPage();
文件。添加页(第页);
//启动新的内容流
PDPageContentStream contentStream=新的PDPageContentStream(文档,页面);
//使用选定字体定义文本内容流,移动光标并在arrayList中绘制文本
对于(int i=0;i),我们需要5个换行符!
*3)将部件放入stringbuffer[i],直到允许一行中的最大字符数限制为止,
*4)循环直到stringbuffer.length<换行符
* 
*/
int linebreaks=text.length()/80;//我需要多少换行符?
字符串[]新文本=新字符串[换行符+1];
字符串tmpText=文本;
String[]parts=tmpText.split(“”;//将每个单词保存到数组元素中
//将字符串中的每个单词拆分为字符串文本数组。
StringBuffer[]StringBuffer=新建StringBuffer[linebreaks+1];//由于要处理文本,因此需要StringBuffer
int i=0;//初始化计数器
int totalTextLength=0;
对于(int k=0;k=parts.length)break;//避免NullPointerException
totalTextLength=totalTextLength+parts[i].length();//计算字符串中的每个单词
if(totalTextLength>80)break;//将每个单词放入stringbuffer,直到字符串长度>80
stringBuffer[k].append(parts[i]);
stringBuffer[k]。追加(“”);
i++;
}
//重置计数器,将换行符文本保存到数组中,最后将其转换为字符串
totalTextLength=0;
newText[k]=stringBuffer[k].toString();
}
返回新文本;
} 
} 

这对我很有效。WordUtils和split的组合

String[] wrT = null;
String s = null;
text = "Job Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque hendrerit lectus nec ipsum gravida placerat. Fusce eu erat orci. Nunc eget augue neque. Fusce arcu risus, pulvinar eu blandit ac, congue non tellus. Sed eu neque vitae dui placerat ultricies vel vitae mi. Vivamus vulputate nullam.";
wrT = WordUtils.wrap(text, 100).split("\\r?\\n");

for (int i=0; i< wrT.length; i++) {
    contents.beginText();
    contents.setFont(PDType1Font.HELVETICA, 10);
    contents.newLineAtOffset(50,600-i*15);
    s = wrT[i];
    contents.showText(s);
    contents.endText(); 
}
String[]wrT=null;
字符串s=null;
text=“工作描述:Lorem ipsum Door sit amet,连续的发展精英。Pellentsque hendrerit lectus nec ipsum Gradida Placelat。Fusce eu erat orci。Nunc eget augue neque。Fusce arcu risus,pulvinar eu blandit ac,congue non tellus。Sed eu neque vitae dui Placelat Ultrices vel vitae mi。Vivamus Vulputte nullam。”;
wrT=WordUtils.wrap(文本,100).split(\\r?\\n”);
对于(int i=0;i
PdfBox和Boxable都会自动换行长度超过单元格宽度的文本部分,因此这意味着如果 单元格宽度=80 句子宽度=100 宽度为20的文本的剩余部分将从下一行开始 (注:我提到的是宽度(句子实际占用的空间)而不是长度(字符数))

如果句子宽度=60, 宽度为20的文本将需要填充单元格的宽度,之后的任何文本都将转到下一行 解决方案:用空格填充此宽度20

单元格的未填充空间=单元格宽度-句子宽度, numberOfSpaces=单元格的未填充空间/单个空间的宽度

    private String autoWrappedHeaderText(String text, float cellWidth) {
    List<String> splitStrings = Arrays.asList(text.split("\n"));
    String wholeString = "";
    for (String sentence : splitStrings) {
        float sentenceWidth = FontUtils.getStringWidth(headerCellTemplate.getFont(), " " + sentence + " ",
                headerCellTemplate.getFontSize());
        if (sentenceWidth < cellWidth) {
            float spaceWidth = FontUtils.getStringWidth(headerCellTemplate.getFont(), " ",
                    headerCellTemplate.getFontSize());
            int numberOfSpacesReq = (int) ((cellWidth - sentenceWidth) / spaceWidth);
            wholeString += sentence;
            for (int counter = 0; counter < numberOfSpacesReq; counter++) {
                wholeString += " ";
            }
        }
    }

    return wholeString;
}
cell = headerRow.createCell(cellWidth * 100 / table.getWidth(), headerText, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
private String autoWrappedHeaderText(字符串文本,浮点单元格宽度){
List splitStrings=Arrays.asList(text.split(“\n”);
字符串“=”;
for(字符串语句:拆分字符串){
float sentenceWidth=FontUtils.getStringWidth(headerCellTemplate.getFont(),“”+句子+“”,
headerCellTemplate.getFontSize());
if(句子宽度<单元格宽度){
float spaceWidth=FontUtils.getStringWidth(headerCellTemplate.getFont(),“”,
headerCellTemplate.getFontSize());
int numberOfSpacesReq=(int)((cellWidth-sentenceWidth)/spaceWidth);
整体字符串+=句子;
对于(int计数器=0;计数器
对每行字符数进行限制似乎不适合大多数字体。而是