Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit pdf page using pdfbox

Tags:

java

edit

pdfbox

How can i edit a pdf page with java and pdfbox by writing in a specific position that i know already in pixels ?

I tried this but it overwrites :

PDDocument document = null;
try {
    document = PDDocument.load(new File("/x/x/x/mypdf.pdf"));
    PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
    PDFont font = PDType1Font.HELVETICA_BOLD;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    page.getContents().getStream();
    contentStream.beginText();
    contentStream.setFont(font, 12);
    contentStream.moveTextPositionByAmount(100, 100);
    contentStream.drawString("Hello");
    contentStream.endText();
    contentStream.close();
    document.save("/x/x/x/mypdf.pdf");
    document.close();
} catch (IOException e) {
    e.printStackTrace();
} catch (COSVisitorException e) {
    e.printStackTrace();
}

Thank you.

like image 217
Monssef Avatar asked Jul 16 '13 19:07

Monssef


2 Answers

You could have used PDFBox, all you are missing is appending to the page. Just change this line:

PDPageContentStream contentStream = new PDPageContentStream(document, page);

to:

PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

Starting from PDFBox 2.0, the boolean appendContent has been replaced by the AppendMode APPEND such that the equivalent of the previous code is now:

PDPageContentStream contentStream = new PDPageContentStream(
    document, page, PDPageContentStream.AppendMode.APPEND, true
);
like image 134
Anita Kulkarni Avatar answered Sep 24 '22 02:09

Anita Kulkarni


I figure it out how to do it, instead of using pdfbox i used iTextpdf, this is the java code i used :

package ma;

import java.io.*;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;

public class editPdf {

public static void main(String[] args) throws IOException,
        DocumentException {

    PdfReader reader = new PdfReader("/Users/Monssef/Desktop/mypdf.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
            "/Users/Leonidas/Desktop/mypdfmodified.pdf"));
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252,
            BaseFont.NOT_EMBEDDED);

        PdfContentByte over = stamper.getOverContent(1);

        over.beginText();
        over.setFontAndSize(bf, 10);
        over.setTextMatrix(107, 107);
        over.showText("page updated");
        over.endText();

    stamper.close();
}

}
like image 45
Monssef Avatar answered Sep 25 '22 02:09

Monssef