Shaheedul  Islam
Shaheedul Islam

Reputation: 125

Page blank in PDDocument after split

I am trying to create a PDDocument and then add two pages to it. 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. 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. 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");
    }

}

Upvotes: 1

Views: 1489

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18956

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)

Upvotes: 1

Related Questions