[英]Page blank in PDDocument after split
I am trying to create a PDDocument
and then add two pages to it. 我正在尝试创建一个
PDDocument
,然后向其添加两个页面。 The first one containing the text "first page" and the second one being blank. 第一个包含文本“第一页”,第二个为空白。 I then split the
PDDocument
and put it into a list. 然后,我分割
PDDocument
并将其放入列表中。 When I try to access the first page (by using the get Method), I save it expecting to see a pdf with the text "first page" on it but all I get it a blank page. 当我尝试访问第一页(通过使用get方法)时,我保存了它,并希望看到带有文本“ first page”的pdf文件,但是我得到的都是空白页。 Any suggestions?
有什么建议么?
package split;
import java.io.File;
import java.util.List;
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;
import org.apache.pdfbox.util.Splitter;
public class pdfSplit {
public static void main(String[] args) throws Exception {
PDPage page1, page2;
page1 = new PDPage();
page2 = new PDPage();
Splitter splitter = new Splitter();
PDDocument document = new PDDocument();
document.addPage(page1);
document.addPage(page2);
List<PDDocument> splittedPDF = splitter.split(document);
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream = new PDPageContentStream(document, page1);
contentStream.beginText();
contentStream.setFont( font, 50 );
contentStream.moveTextPositionByAmount( 100, 700 );
contentStream.drawString( "First page" );
contentStream.endText();
contentStream.close();
document = splittedPDF.get(0); //No effect
document.save("Random.pdf");
}
}
Your page is blank because you do the split before writing to the page content stream. 您的页面为空白,因为您在写入页面内容流之前先进行了拆分。 Solution: move the splitting code to after closing your content stream.
解决方案:关闭内容流后,将拆分代码移至。 Correct code thus looks like this:
正确的代码如下所示:
PDPage page1, page2;
page1 = new PDPage();
page2 = new PDPage();
Splitter splitter = new Splitter();
PDDocument document = new PDDocument();
document.addPage(page1);
document.addPage(page2);
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream = new PDPageContentStream(document, page1);
contentStream.beginText();
contentStream.setFont(font, 50);
contentStream.moveTextPositionByAmount(100, 700);
contentStream.drawString("First page");
contentStream.endText();
contentStream.close();
// now the page is filled!
List<PDDocument> splittedPDF = splitter.split(document);
document = splittedPDF.get(0);
document.save("Random.pdf");
(This answer was done with version 1.8.10) (此答案是在1.8.10版中完成的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.