iText, loading an existing PDF and adding text to it - java

I have an existing PDF, a simple 2 page form. I need to load the PDF, and in relevant pages in the form, insert text so that it's unique to each person that downloads the PDF.
My initial idea was the load the PDF, and on page one simply overlay the text in the relevant place, however when I try the code below, all this does is add the text to the end of page 1, rather than at the top where I'm telling it to position it.
PdfReader pdfReader = new PdfReader(inputFile);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(outputFile));
for(int i=1; i<= pdfReader.getNumberOfPages(); i++){
PdfContentByte content = pdfStamper.getOverContent(i);
if (i == 1) {
//Text over the existing page
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
content.beginText();
content.setFontAndSize(bf, 18);
content.showTextAligned(PdfContentByte.ALIGN_LEFT, "This is some text " + i, 0, 0, 0);
content.endText();
}
}
Could someone advise where I might be going wrong please?

Related

Printing a PDF enters a long and slow flattening process

I am programmatically trying to create an pdf by superimposing two pdf files using itextpdf. The PDF that was made goes into this flattening process for some reason, how do I skip flattening or make the process faster.
PdfReader reader = new PdfReader(template);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfReader r;
PdfImportedPage page;
int i=1;
for (String path : patterns) {
r = new PdfReader(path);
for(int j=1;j<=r.getNumberOfPages();j++) {
page = stamper.getImportedPage(r, j);
PdfContentByte canvas = stamper.getUnderContent(i++);
canvas.addTemplate(page, 0, 0);
stamper.getWriter().freeReader(r);
}
r.close();
}
stamper.close();
The PDF that was generated from Adobe Illustrator had an masked image instead of a proper component. I am sorry if the answer seems vague but I am not a designer but the flattening process happens when the one or more of the original PDFs that are being merged aren't proper.

Add text to a specific page of a pdf using iText

I need create a tool that adds a hyperlink every other page for a pdf file.
I followed the iText documentation and I managed to add the hyperlink but only on the first page.
My code:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
Font bold = new Font(FontFamily.HELVETICA, 30, Font.BOLD);
PdfReader reader = new PdfReader(src);
int count = reader.getNumberOfPages();
Utils.logInfoMessage("Number of pages: " + count, mLogList);
if(count < 1) {
Utils.logErrorMessage("file : " + src + " has no pages", mLogList);
return;
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfContentByte canvas = stamper.getOverContent(1);
PdfGState gState = new PdfGState();
gState.setFillOpacity(0.1f);
canvas.setGState(gState);
Chunk chunk = new Chunk("www.google.com", bold);
chunk.setAnchor("https://www.google.ro/");
Phrase phrase = new Phrase("");
phrase.add(chunk);
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(36, 700, 559, 750);
ct.addText(phrase);
ct.go();
stamper.close();
reader.close();
}
Any ideas how to add the hyperlink/text only on a specific page?
You wrote:
I followed the iText documentation and I managed to add the hyperlink but only on the first page
This is the iText documentation: PdfStamper
getOverContent
public PdfContentByte getOverContent(int pageNum)
Gets a PdfContentByte to write over the page of the original
document.
Parameters:
pageNum - the page number where the extra content is written
Returns:
a PdfContentByte to write over the page of the original document
This is the code you wrote:
PdfContentByte canvas = stamper.getOverContent(1);
You used 1 as the value for pageNum.
Now you tell me: if you choose 1 as the page number, then why are you surprised that all the content you add is only added on the first page?
IMPORTANT:
You write
I followed the iText documentation
I assume that you refer to the official documentation on the official iText web page: https://itextpdf.com
If that is correct, then why are you still using an old version of iText? The current version is 7.1.2, and the PdfStamper class no longer exists in that version. As explained in chapter 5 of the iText 7 Jump-Start tutorial adding content to an existing PDF is done differently nowadays.
FYI: there are some more tutorials here: https://developers.itextpdf.com/books

iText add image to pdf - setAbsolutePosition [duplicate]

I am trying to read one PDF and copy its data into another PDF. The first PDF contains some text and images and I wish to write an image in the second PDF exactly where the text ends(which is basically the end of the PDF file). RIght now it just prints at the top. How can I make this change?
PdfReader reader = null;
reader = new PdfReader(Var.input);
Document document=new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document,new FileOutputStream(Var.output));
PdfImportedPage page = writer.getImportedPage(reader, 1);
reader.close();
document.open();
PdfContentByte cb = writer.getDirectContent();
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
Image image = null;
image = Image.getInstance (Var.qr);
document.add(image);
document.close();
Try this:
First get the location/co-ords of where the image needs to go, then simply add the second line from below to your code so the image is inserted at that location "X, Y"
Image image = Image.getInstance(String RESOURCE);
image.setAbsolutePosition(X, Y);
writer.getDirectContent().addImage(image);
Take a look here for some examples in iText 5: https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions
You should use a PdfStamper instead of a PdfWriter with imported pages. Your approach throws away all interactive contents. You can use sorifiend's idea there, too.
To determine where the text on the given page ends, have a look at the iText in Action, 2nd edition example ShowTextMargins which parses a PDF and ads a rectangle showing the text margin.

PdfStamper not working in IE, or Adobe, but works in Chrome and FF

So Weird, I am generating a PDF using FlyingSaucer, then adding a footer to the PDF. The footer works in Chrome and FF, but not IE. But if I download the PDF, even from Chrome, where the text is there, open it locally with Adobe, it is not... I dont get it.
Code:
ByteArrayOutputStream os = originalPDF.getOutputStream();
ByteArrayOutputStream newos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(os.toByteArray());
PdfStamper stamper = new PdfStamper(reader, newos);
for(int i=1; i<= reader.getNumberOfPages(); i++){
Rectangle pageSize = reader.getPageSize(i);
PdfContentByte content = stamper.getUnderContent(i);
BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, "utf8", false);
content.setFontAndSize(baseFont, 15);
content.setRGBColorFill(0, 0, 0);
content.showTextAligned(PdfContentByte.ALIGN_LEFT, "Page "+i, 3, 5, 0);
content.showTextAligned(PdfContentByte.ALIGN_RIGHT, " - Printed: "+DateUtil.date2str_MM_dd_yyyy(new Date()), pageSize.getWidth()-3, 5, 0);
}
stamper.close();
request.getSession().setAttribute("file", newos.toByteArray());
Any Ideas?
#mkl
EDIT:
I cannot post the PDF, sensitive information and all that BUT, if I change the code to:
PdfContentByte content = stamper.getUnderContent(i);
String msg = "Page "+i+" - Printed: "+DateUtil.datetime2str_MM_dd_yyyy_h_mm_a(new Timestamp(new Date().getTime()));
ColumnText.showTextAligned(content, PdfContentByte.ALIGN_CENTER, new Phrase(msg), center, 5, 0);
It works on all browsers and Adobe. So clearly my font and/or encoding is wrong. Any suggestions for proper encoding?

Image positioning in iText - Java

I am trying to read one PDF and copy its data into another PDF. The first PDF contains some text and images and I wish to write an image in the second PDF exactly where the text ends(which is basically the end of the PDF file). RIght now it just prints at the top. How can I make this change?
PdfReader reader = null;
reader = new PdfReader(Var.input);
Document document=new Document();
PdfWriter writer = null;
writer = PdfWriter.getInstance(document,new FileOutputStream(Var.output));
PdfImportedPage page = writer.getImportedPage(reader, 1);
reader.close();
document.open();
PdfContentByte cb = writer.getDirectContent();
// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);
// Add your new data / text here
Image image = null;
image = Image.getInstance (Var.qr);
document.add(image);
document.close();
Try this:
First get the location/co-ords of where the image needs to go, then simply add the second line from below to your code so the image is inserted at that location "X, Y"
Image image = Image.getInstance(String RESOURCE);
image.setAbsolutePosition(X, Y);
writer.getDirectContent().addImage(image);
Take a look here for some examples in iText 5: https://itextpdf.com/en/resources/examples/itext-5-legacy/chapter-3-adding-content-absolute-positions
You should use a PdfStamper instead of a PdfWriter with imported pages. Your approach throws away all interactive contents. You can use sorifiend's idea there, too.
To determine where the text on the given page ends, have a look at the iText in Action, 2nd edition example ShowTextMargins which parses a PDF and ads a rectangle showing the text margin.

Categories