I would like to modify a existing pdf document and add a watermark image. How can I do this without to create a new file?
I think it's a stupid solution to create a temp pdf. Delete the source file and rename the temp pdf like the source file!?
Here my example code but there I'm creating a new destination file.
Regards
private static void PdfApplication(String filePath) {
PdfReader pdfReader = new PdfReader(filePath);
Stream outputStream = new FileStream(newFilePath, FileMode.Open, FileAccess.Write, FileShare.None);
PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream,'1', true);
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) {
pdfStamper.FormFlattening = false;
iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.4F;
pdfData.SetGState(graphicsState);
pdfData.BeginText();
FileStream fileStreamImage = new FileStream(watermark.jpg", FileMode.Open);
iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fileStreamImage), ImageFormat.Jpeg);
float width = pageRectangle.Width;
float height = pageRectangle.Height;
jpeg.ScaleToFit(width, height);
jpeg.SetAbsolutePosition(width / 2 - jpeg.Width / 2, height / 2 - jpeg.Height / 2);
jpeg.SetAbsolutePosition(50, 50);
jpeg.Rotation = 250;
pdfData.AddImage(jpeg);
pdfData.EndText();
}
pdfStamper.Close();
outputStream.Close();
outputStream.Dispose();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…