Reputation: 94
I am trying to add annotations to every Page which gets copied to my new pdf but not able to do that...
Here is my code.
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import java.awt.*;
import java.io.FileOutputStream;
public class Annotations {
public static void main(String[] args) {
try {
PdfReader reader = new PdfReader("string-to-pdf.pdf");
Document document = new Document(reader.getPageSizeWithRotation(1));
PdfCopy copy = new PdfCopy(document,
new FileOutputStream("temp.pdf"));
copy.setPdfVersion(PdfWriter.VERSION_1_5);
document.open();
for(int i = 1; i <=reader.getNumberOfPages();i++){
copy.addPage(copy.getImportedPage(reader,i));
copy.addAnnotation(PdfAnnotation.createLink(copy, new Rectangle(200f, 700f, 30455454f, 800f), PdfAnnotation.HIGHLIGHT_TOGGLE, PdfAction.javaScript("app.alert('Hello');\r", copy)));
}
document.newPage();
// page 3
PdfContentByte pcb = new PdfContentByte(copy);
pcb.setColorFill(new Color(0xFF, 0x00, 0x00));
document.close();
} catch (Exception de) {
de.printStackTrace();
}
}
}
the files are getting copied but can't see the annotations in the new file.
Upvotes: 0
Views: 564
Reputation: 96064
PdfCopy
is for faithful page copying, not for creation; thus, modification routines inherited from PdfWriter
are disabled, e.g.
@Override
public void addAnnotation(PdfAnnotation annot) { }
Dedicated manipulations are possible, though, by means of page stamps, cf. createPageStamp
. The JavaDocs of that method contain some example usage code including an addition of an annotation:
PdfImportedPage page = copy.getImportedPage(reader, 1);
PdfCopy.PageStamp ps = copy.createPageStamp(page);
ps.addAnnotation(PdfAnnotation.createText(copy, new Rectangle(50, 180, 70, 200), "Hello", "No Thanks", true, "Comment"));
PdfContentByte under = ps.getUnderContent();
under.addImage(img);
PdfContentByte over = ps.getOverContent();
over.beginText();
over.setFontAndSize(bf, 18);
over.setTextMatrix(30, 30);
over.showText("total page " + totalPage);
over.endText();
ps.alterContents();
copy.addPage(page);
Beware, though, applying a PageStamp
like this actually manipulates the original PdfReader
. Afterwards, therefore, don't continue using the PdfReader
instance assuming its contents are the original contents, in particular the pagestamped copied pages are dirty.
Upvotes: 2