Remove image in pdf document with itextsharp - itext

I have a requirement to add image to pdf documents and being able later to remove the image if needed.
I manage to add image to documents with this code :
iText.Kernel.Geom.Rectangle pagesize;
PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourceFile), new PdfWriter(destinationPath));
int n = pdfDoc.GetNumberOfPages();
ImageData img = ImageDataFactory.Create(image_WM_Path);
for (int i = 1; i <= n; i++)
{
pagesize = pdfDoc.GetPage(i).GetPageSizeWithRotation();
float f = pagesize.GetWidth() / (1.5f * img.GetWidth());
float wImage = img.GetWidth() * f;
float hImage = img.GetHeight() * f;
iText.Kernel.Geom.Rectangle rectangle = new iText.Kernel.Geom.Rectangle(pagesize.GetRight() - wImage, pagesize.GetBottom(),wImage, hImage );
PdfStampAnnotation stamp = new PdfStampAnnotation(rectangle);
stamp.SetStampName(new PdfName("MyCustomStamp"));
PdfFormXObject xObj = new PdfFormXObject(new iText.Kernel.Geom.Rectangle(wImage, hImage));
PdfCanvas canvas = new PdfCanvas(xObj, pdfDoc);
canvas.AddImage(img, 0, 0, wImage, false);
stamp.SetNormalAppearance(xObj.GetPdfObject());
pdfDoc.GetPage(i).AddAnnotation(stamp);
}
pdfDoc.Close();
Is it the correct way to add image as annotation ?
Do i really put an id with the SetStampName method ?
I don't manage to retrieve the annotation in the page's PdfDictionary annotation array, the array is null :
PdfArray annotations = pageDict.GetAsArray(PdfName.Annotation);
Thanks for your help

Related

How to NOT flatten the image applied in a pdf with Itext in c#?

I need to apply an image on all my pages from my PDF, but without flattening it ( I want to have the ability to move it in my PDF reader afterwards)
My code:
String basePath = "d:\\zPDF\\";
DirectoryInfo d = new DirectoryInfo(basePath);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.pdf"); //Getting Text files
List<string> listS = new List<string>();
foreach (FileInfo file in Files)
{
listS.Add(file.Name);
}
foreach (string s in listS)
{
using (System.IO.Stream inputPdfStream = new FileStream(basePath + s, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
//using (System.IO.Stream inputImageStream = new FileStream(basePath + "x1.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream inputImageStream2 = new FileStream(basePath + "x2.wmf", FileMode.Open, System.IO.FileAccess.Read, FileShare.Read))
using (System.IO.Stream outputPdfStream = new FileStream(basePath + "zResult" + s, FileMode.Create, System.IO.FileAccess.Write, FileShare.None))
{
var reader = new PdfReader(inputPdfStream);
var stamper = new PdfStamper(reader, outputPdfStream);
//stamper.FormFlattening = true;
//stamper.FreeTextFlattening = true;
int numberOfPages = reader.NumberOfPages;
Image myImage = Image.GetInstance(inputImageStream2);
float f-Image1, f-Image2;
for (int i = 1; i <= numberOfPages; i++)
{
int nr, plusMinus = 25;
Rectangle mediabox = reader.GetPageSize(i);
int getTOP = (int)mediabox.GetTop(0);
int getRight = (int)mediabox.GetRight(0);
var pdfContentByte = stamper.GetOverContent(i);
nr = getRight - 600;
f-Image1 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
nr = 40;
f-Image2 = row1(nr, nr + plusMinus);
//row1 - generates a random number between those 2 values
myImage.SetAbsolutePosition(f-Image1, f-Image2);
myImage.RotationDegrees = row1(-35, 35);
pdfContentByte.AddImage(myImage);
}
stamper.Close();
}
I've tried:
stamper.FormFlattening = false;
stamper.FreeTextFlattening = false;
but no results. The image is still flatten.
I think, after I've read some posts, that I need to set up my PdfStamper in useAppendMode() but I don't know how should I do this and, I don't know if this is this right direction.

Migrating add image to pdf from iText to PDFBox

In our project we are using iText 5.x version to manipulate PDF files and working to migrate that implementation with PDFBox 2.x version.
There is one add image to pdf page scenario and I have converted that code into PDFBox as good as I could do. :) In existing implementation(iText) they add image in template using PdfTemplate and added that template in annotation using PdfAnnotation class.
I don't know how to do that using PDFBox. Also please check that I migrated existing implementation properly or not as I'm newbie in PDF library using Java.
Add Image to PDF(Using iText):
Document document = null;
PdfReader pdfReader = null;
pdfReader = new PdfReader(SourceFilePath());
//we retrieve the total number of pages and the page size
int total = pdfReader.getNumberOfPages();
Rectangle rectangle = pdfReader.getPageSizeWithRotation(1);
document = new Document(rectangle);
PdfImportedPage page;
PdfCopy.PageStamp stamp;
// step 2: we create a PdfCopy object that listens to the document.
PdfCopy copy = new PdfCopy(document, new FileOutputStream(DestinationFilePath(false));
document.open();
// step 4: adding the content
for (int i = 1; i <= total; i++) {
page = copy.getImportedPage(pdfReader, i);
if(i == 1 || aBarcodeVO.getDisplacementVO().isApplyForAllPages()){
BufferedImage bufferedImage = getImage();
Image img = Image.getInstance(bufferedImage, null);
img.scaleToFit(qrImageSize, qrImageSize);
PdfName imgKey = new PdfName(aBarcodeVO.getImgUniqueId() + i);
Rectangle rectPage = pdfReader.getPageSizeWithRotation(i);
stamp = copy.createPageStamp(page);
PdfImage stream = new PdfImage(img, "", null);
stream.put(imgKey, imgKey);
PdfIndirectObject ref = copy.addToBody(stream);
int rotation = pdfReader.getPageRotation(i);
Rectangle cropBoxRect = pdfReader.getCropBox(i);;
//Explicitly Apply rotation to crop box rectangle.
for (int j = 0; j < (rotation/90); j++) {
cropBoxRect = cropBoxRect.rotate();
}
//added Image in template and template in Annotation and finally annotation is added in PDF through PdfCopy.PageStamp
PdfTemplate template = PdfTemplate.createTemplate(copy, img.getPlainWidth(), img.getPlainHeight());
img.setAbsolutePosition(0, 0);
img.setRotationDegrees(rotation);
img.setDirectReference(ref.getIndirectReference());
template.addImage(img);
Rectangle rect = new Rectangle(rectLlx, rectLly, rectUrx, rectUry);
rect.setBorderWidth(0.5f);
rect.setBorderColor(new BaseColor(0xFF, 0x00, 0x00));
PdfAnnotation annotation = PdfAnnotation.createStamp(copy, rect, null, "AnnotationOnly");
annotation.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, template);
annotation.setFlags(PdfAnnotation.FLAGS_PRINT + PdfAnnotation.FLAGS_LOCKED);
annotation.setRotate(rotation);
PdfName annotKey = getAnnotKey(i);
annotation.put(annotKey, annotKey);
stamp.addAnnotation(annotation);
stamp.alterContents();
}
copy.addPage(page);
}
copy.freeReader(pdfReader);
try {
if (document != null) {
document.close();
}
} catch (Exception e) {
System.out.println("Exception in handleAddBarCode() while closing():document:" + e);
}
try {
if (pdfReader != null) {
pdfReader.close();
}
} catch (Exception e) {
System.out.println("Exception in handleAddBarCode() while closing():pdfReader:" + e);
}
Add Image to PDF(Using PDFBox):
PDDocument pdDocument = PDDocument.load(new File(SourceFilePath()));
int total = pdDocument.getNumberOfPages();
PDPage page = pdDocument.getDocumentCatalog().getPages().get(0);
PDRectangle rectangle = getRotatedMediaBox(page);
PDPage pdPage = new PDPage(rectangle);
PDDocument newDocument = new PDDocument();
for (int i = 0; i < total; i++) {
pdPage = newDocument.importPage(pdDocument.getPage(i));
PDRectangle pageRect = getRotatedMediaBox(pdPage);
int rotation = pdPage.getRotation();
PDRectangle cropBoxRect = page.getCropBox();
//Calculate margin between crop box rectangle and page rectangle.
float[] margins = getCropBoxMargin(pageRect, cropBoxRect, rotation);
if (rotation == 90 || rotation == 270) {
cropBoxRect = new PDRectangle(cropBoxRect.getLowerLeftY(), cropBoxRect.getLowerLeftX(), cropBoxRect.getHeight(),
cropBoxRect.getWidth());
}
BufferedImage bufferedImage = getImage();
PDPageContentStream pageContentStream = new PDPageContentStream(newDocument, pdPage,
PDPageContentStream.AppendMode.APPEND, true);
PDImageXObject image = JPEGFactory.createFromImage(newDocument, bufferedImage);
if (rotation == 90 || rotation == 270) {
Matrix matrix = Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0);
PDRectangle cropBox = pdPage.getCropBox();
float tx = (cropBox.getLowerLeftX() + cropBox.getUpperRightX()) / 2;
float ty = (cropBox.getLowerLeftY() + cropBox.getUpperRightY()) / 2;
Rectangle rectang = cropBox.transform(matrix).getBounds();
float scale = Math.min(cropBox.getWidth() / (float)rectang.getWidth(), cropBox.getHeight() / (float)rectang.getHeight());
pageContentStream.transform(Matrix.getTranslateInstance(tx, ty));
pageContentStream.transform(matrix);
pageContentStream.transform(Matrix.getScaleInstance(scale, scale));
pageContentStream.transform(Matrix.getTranslateInstance(-tx, -ty));
}
pageContentStream.drawImage(image, rectLlx, rectLly, qrImageSize, qrImageSize);
pageContentStream.close();
}
newDocument.save(new File(DestinationFilePath(false)));
newDocument.close();
pdDocument.close();
Please help me on this or at least looking forward for your suggestions for code needs to rectify of PDFBox implementation.

Hundred thousands of datatable records to PDF in web API

I'm trying to create PDF from the DataTable in web api using ADO.Net. Unfortunately based on filters some times I may get very less records & able to download without any problem. Sometimes may be very huge like 200 thousand of records. When I'm checking in local my system its getting hang while converting the dt to PDF. My code is like below:
private FileContentResult ExportPDF(DataTable dataTable)
{
string Name = "Logs";
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
byte[] content = null;
try
{
string[] columnNames = (from dc in dataTable.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
int count = columnNames.Length;
object[] array = new object[count];
dataTable.Rows.Add(array);
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
HeaderFooter header = new HeaderFooter(new Phrase(Name), false);
// Remove the border that is set by default
header.Border = iTextSharp.text.Rectangle.TITLE;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = Element.ALIGN_CENTER;
pdfDoc.Header = header;
// Header.
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1; pdfTable.Width = 100;
pdfTable.Padding = 1; pdfTable.Spacing = 4;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Chunk chunkCols = new Chunk();
iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.Black);
chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
content = mStream.ToArray();
return File(content, "application/pdf", "LogReports.pdf");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Write Image on Text in PDF Form Fields using ITextSharp

When I tried to write an image on Text Field, the image is written behind text. It is working for normal text and image but not on Form Fields. I want to write image on Text that covers text behind.
void OldMethod()
{
string path = #"C:\Users\";
string OutLocation = path + "New.pdf";
string Old = path + "Old.pdf";
PdfReader reader1 = new PdfReader(Old);
using (FileStream fs = new FileStream(OutLocation, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
int pageCount1 = reader1.NumberOfPages;
//Create a new layer
for (int i = 1; i <= pageCount1; i++)
{
iTextSharp.text.Rectangle rect = reader1.GetPageSize(i);
PdfContentByte cb = stamper.GetOverContent(i);
AcroFields Fields = stamper.AcroFields;
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
Fields.SetField("Price", #"1323423345");
Fields.SetFieldProperty("Price", "TEXTCOLOR", BaseColor.RED, null);
string Img = path + "red_slash.jpg";
iTextSharp.text.Image jpeg = Image.GetInstance(System.Drawing.Image.FromFile(Img), ImageFormat.Jpeg);
float width = 100;
float height = 200;
jpeg.ScaleToFit(width, height);
jpeg.SetAbsolutePosition(210, 315);
cb.AddImage(jpeg);
}
}
}
}
Here I need to write the image on the field "Price"

iTextSharp - Adding an image and resize pages in PDF

I have a PDF file which I need to insert an image on the 1st page and then resize the original size from A4 to some other size.
I manage to add an image into the PDF but not resizing it with the following code:
string pdfFile = #"C:\Temp\a.pdf";
PdfReader reader = new PdfReader(pdfFile);
PdfStamper stamper = new PdfStamper(reader, new FileStream(#"C:\Temp\out.pdf", FileMode.Create), PdfWriter.VERSION_1_5);
PdfContentByte writer = stamper.GetOverContent(1);
stamper.FormFlattening = true;
stamper.SetFullCompression();
Image topImage = Image.GetInstance(#"C:\Temp\c.jpg");
topImage.ScalePercent(19f);
topImage.SetAbsolutePosition(142, 700);
writer.AddImage(topImage);
Document myPDF = writer.PdfDocument;
myPDF.SetPageSize(PageSize.A3);
stamper.Close();
stamper = null;
Is there anything wrong or missing in my code?
Below is how a PDF can be resized:
private string PdfResize(string tmpPdfFilename, string resultRootName)
{
try
{
string newPdfFilename = resultRootName + ".pdf";
PdfReader resizeReader = new PdfReader(tmpPdfFilename);
Rectangle newRect = new Rectangle(0, 0, Convert.ToSingle(_pdfNewSizeW), Convert.ToSingle(_pdfNewSizeH));
Document doc = new Document(newRect);
Document.Compress = true;
PdfWriter resizeWriter = PdfWriter.GetInstance(doc, new FileStream(newPdfFilename, FileMode.Create));
doc.Open();
PdfContentByte cb = resizeWriter.DirectContent;
for (int pageNumber = 1; pageNumber <= resizeReader.NumberOfPages; pageNumber++)
{
PdfImportedPage page = resizeWriter.GetImportedPage(resizeReader, pageNumber);
cb.AddTemplate(page, newRect.Width / resizeReader.GetPageSize(pageNumber).Width, 0, 0,
newRect.Height / resizeReader.GetPageSize(pageNumber).Height, 0, 0);
doc.NewPage();
}
doc.Close();
doc = null;
return newPdfFilename;
}
catch (Exception exp)
{
return String.Empty;
}
}
Despite being an older thread the original question & thread was very helpful recently.
Here's another version that processes the Pdf input as a byte array instead of file path (more helpful for web app environment), and handles all IDisposable references...
public static byte[] ResizePdfPageSize(byte[] pdfBytes, Rectangle pageSize)
{
Document.Compress = true;
using (var outputMemoryStream = new MemoryStream())
using (var targetDoc = new Document(pageSize))
using (var pdfReader = new PdfReader(pdfBytes))
using (var pdfWriter = PdfWriter.GetInstance(targetDoc, outputMemoryStream))
{
targetDoc.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
var pageCount = pdfReader.NumberOfPages;
for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++)
{
PdfImportedPage page = pdfWriter.GetImportedPage(pdfReader, pageNumber);
var currentPageSize = pdfReader.GetPageSize(pageNumber);
var scaledPageWidth = pageSize.Width / currentPageSize.Width;
var scaledPageHeight = pageSize.Height / currentPageSize.Height;
pdfContentByte.AddTemplate(
page,
scaledPageWidth,
0, 0,
scaledPageHeight,
0, 0
);
//Move document cursor to next Page!
targetDoc.NewPage();
}
targetDoc.Close();
byte[] finalFileBytes = outputMemoryStream.ToArray();
return finalFileBytes;
}
}
Usage with pre-set PageSizes from iTextSharp is very handy:
var originalPdfBytes = File.ReadAllBytes(fileInfo.FullName);
var resizedBytes = PdfHelper.ResizePdfPageSize(originalPdfBytes, PageSize.A4);
File.WriteAllBytes(fileName, resizedBytes);
EDIT: The above method answers the core question and got me where I needed to get for my issues. However, after working on this and ironing out numerous issues and shortcomings of the above simplified method, I've now put the whole helpful code base on github to share for anyone else interested. The github PdfHelpers project now handle aspect ratio better, page margins, rotation of content for better scaling as landscape, content that's already rotated (in my limited test cases), etc. while also providing other helpful code for simple Pdf tasks.
https://github.com/cajuncoding/PdfHelpers