iText Stamping - Java [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-04 10:03:15
The Macedon

I made it happen' :)

Here is the code used to add custom text to document using iText without invalidating digital signatures.

//Read the source PDF
PdfReader reader = new PdfReader(inputstream);
//Create PdfStamp object
stamp = new PdfStamper(reader, new FileOutputStream(file), '\0', true);

//Create the proper annotation
PdfAnnotation annot = PdfAnnotation.createFreeText(stamp.getWriter(),  new Rectangle(150, 150, 200, 200), "Annotation 1", pcb);
annot.setFlags(PdfAnnotation.FLAGS_PRINT);

//Insert the annotation         
stamp.addAnnotation(annot, 1);
//Close the stamp
stamp.close();  

EDIT:

For inserting image stamp to the document without invalidating the digital signatures I used this code:

//Read the pdf 
PdfReader reader = new PdfReader(inputstream);
//Use PdfStamper in append mode
stamp = new PdfStamper(reader, new FileOutputStream(file), '\0', true); 

//Read the image
Image img = Image.getInstance(ImageIO.read(imgStream), null);

float w = img.getScaledWidth();
float h = img.getScaledHeight();
Rectangle location = new Rectangle(70, 770 - h, 70 + w, 770);

//Create stamp annotation           
PdfAnnotation stampAnnot = PdfAnnotation.createStamp(stamp.getWriter(), location, null, "ITEXT");
img.setAbsolutePosition(0, 0);
//Create new PdfContentByte from the stamp writer
//If you use cd = stamp.getOverContent(1) - you'll invalidate the signatures
PdfContentByte cb = new PdfContentByte(stamp.getWriter());
PdfAppearance app = cb.createAppearance(w, h);
app.addImage(img);
stampAnnot.setAppearance(PdfName.N, app);
stampAnnot.setFlags(PdfAnnotation.FLAGS_PRINT);

stamp.addAnnotation(stampAnnot, 1);
reader.close();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!