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.
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
);
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With