Reading jpg metadata with javax.imageio sometimes throw JFIF APP0 must be first marker after SOI - metadata

I have to set watermark on image (bytes[] original image), i can't use a ImageIO.read() because this method ignore metadata that i also need in future processes, so i had to ImageReader. This method work nice for some pictures and for some doesn't (both of them are .JPG)
private InputStream createWatermark(byte[] bytes, Long position) {
ByteArrayOutputStream os = new ByteArrayOutputStream(255);
ImageOutputStream ios;
try {
ios = ImageIO.createImageOutputStream(os);
ImageReader reader = ImageIO.getImageReadersBySuffix(getExtensionFromImage(bytes)).next();
reader.setInput(ImageIO.createImageInputStream(new ByteArrayInputStream(bytes)));
IIOMetadata metadata = reader.getImageMetadata(0);
BufferedImage bi = reader.read(0);
Graphics2D g2d = (Graphics2D) bi.getGraphics();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String watermark = LocalDateTime.now().format(formatter);
g2d.setColor(Color.WHITE);
g2d.setFont(new Font("Arial", Font.BOLD, bi.getWidth() / 45));
FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);
int x = getX(position, bi, rect);
int y = getY(position, bi);
g2d.drawString(watermark, x, y);
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(getExtensionFromImage(bytes));
ImageWriter writer = iter.next();
writer.setOutput(ios);
ImageWriteParam iwParam = writer.getDefaultWriteParam();
iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
IIOImage image = new IIOImage(bi, null, metadata);
writer.write(null, image, iwParam);
writer.dispose();
bytes = os.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(bytes);
}
javax.imageio.IIOException: JFIF APP0 must be first marker after SOI
on line:
IIOMetadata metadata = reader.getImageMetadata(0);

Related

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.

multiple signing pdf iText

im trying to sign a document several times simulating a signature by different users using itext 5.5.13.1, PdfStamper is on AppendMode. If document has not signatures, the certification level is CERTIFIED_NO_CHANGES_ALLOWED or CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, else i dont set this param for PdfSignatureAppearence. After the second signing the first signature is invalid, because the document was changed. Any ideas how to fix this?
Here's my code:
public void Sign(string Thumbprint, string document, string logoPath) {
X509Certificate2 certificate = FindCertificate(Thumbprint);
PdfReader reader = new PdfReader(document);
//Append mode
PdfStamper st = PdfStamper.CreateSignature(reader, new FileStream(SignedDocumentPath(document), FileMode.Create, FileAccess.Write), '\0', null, true);
int signatureWidth = 250;
int signatureHeight = 100;
int NewXPos = 0;
int NewYPos = 0;
SetStampCoordinates(reader, st, ref NewXPos, ref NewYPos, signatureWidth, signatureHeight);
PdfSignatureAppearance sap = st.SignatureAppearance;
if (reader.AcroFields.GetSignatureNames().Count == 0)
{
SetSignatureFieldOptions(certificate, sap, reader, "1", 1, NewXPos, NewYPos, signatureWidth, signatureHeight);
}
else {
SetSignatureFieldOptions(certificate, sap, reader, "2", NewXPos, NewYPos, signatureWidth, signatureHeight);
}
Image image = Image.GetInstance(logoPath);
image.ScaleAbsolute(50, 50);
Font font1 = SetFont("TIMES.TTF", BaseColor.BLUE, 10, 0);
Font font2 = SetFont("TIMES.TTF", BaseColor.BLUE, 8, 0);
PdfTemplate layer = sap.GetLayer(2);
Chunk chunk1 = new Chunk($"\r\nДОКУМЕНТ ПОДПИСАН\r\nЭЛЕКТРОННОЙ ПОДПИСЬЮ\r\n", font1);
Chunk chunk2 = new Chunk($"Сертификат {certificate.Thumbprint}\r\n" +
$"Владелец {certificate.GetNameInfo(X509NameType.SimpleName, false)}\r\n" +
$"Действителен с {Convert.ToDateTime(certificate.GetEffectiveDateString()).Date.ToShortDateString()} " +
$"по {Convert.ToDateTime(certificate.GetExpirationDateString()).Date.ToShortDateString()}\r\n", font2);
PdfTemplate layer0 = sap.GetLayer(0);
image.SetAbsolutePosition(5, 50);
layer0.AddImage(image);
Paragraph para1 = SetParagraphOptions(chunk1, 1, 50, 0, 2, 1.1f);
Paragraph para2 = SetParagraphOptions(chunk2, 0, 5, 15, 0.5f, 1.1f);
ColumnText ct = new ColumnText(layer);
ct.SetSimpleColumn(3f, 3f, layer.BoundingBox.Width - 3f, layer.BoundingBox.Height);
ct.AddElement(para1);
ct.AddElement(para2);
ct.Go();
layer.SetLineWidth(3);
layer.SetRGBColorStroke(0, 0, 255);
layer.Rectangle(0, 0, layer.BoundingBox.Right, layer.BoundingBox.Top);
layer.Stroke();
EncryptDocument(certificate, sap);
}
public X509Certificate2 FindCertificate(string Thumbprint) {
X509Store store = new X509Store("My", StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2Collection found = store.Certificates.Find(
X509FindType.FindByThumbprint, Thumbprint, true);
X509Certificate2 certificate = found[0];
if (certificate.PrivateKey is Gost3410_2012_256CryptoServiceProvider cert_key)
{
var cspParameters = new CspParameters
{
KeyContainerName = cert_key.CspKeyContainerInfo.KeyContainerName,
ProviderType = cert_key.CspKeyContainerInfo.ProviderType,
ProviderName = cert_key.CspKeyContainerInfo.ProviderName,
Flags = cert_key.CspKeyContainerInfo.MachineKeyStore
? (CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore)
: (CspProviderFlags.UseExistingKey),
KeyPassword = new SecureString()
};
certificate = new X509Certificate2(certificate.RawData)
{
PrivateKey = new Gost3410_2012_256CryptoServiceProvider(cspParameters)
};
}
return certificate;
}
public Font SetFont(string TTFFontName, BaseColor color, float size, int style) {
string ttf = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), TTFFontName);
BaseFont baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, size, style);
font.Color = color;
return font;
}
public Paragraph SetParagraphOptions(Chunk chunk, int ParagraphAligment, float marginLeft, float marginTop, float fixedLeading, float multipledLeading) {
Paragraph paragraph = new Paragraph();
paragraph.Alignment = ParagraphAligment;
paragraph.IndentationLeft = marginLeft;
paragraph.SpacingBefore = marginTop;
paragraph.SetLeading(fixedLeading, multipledLeading);
paragraph.Add(chunk);
return paragraph;
}
public string SignedDocumentPath(string document) {
string filename = String.Concat(Path.GetFileNameWithoutExtension(document), "_signed.pdf");
string path = Path.Combine(Path.GetDirectoryName(document), filename);
return path;
}
public void SetSignatureFieldOptions(X509Certificate2 certificate, PdfSignatureAppearance sap, PdfReader reader, string field, int level, int XPos, int YPos, int width, int height)
{
X509CertificateParser parser = new X509CertificateParser();
try
{
Rectangle rectangle = new Rectangle(XPos, YPos, XPos + width, YPos + height);
sap.SetVisibleSignature(rectangle, reader.NumberOfPages, field);
sap.Certificate = parser.ReadCertificate(certificate.RawData);
sap.Reason = "I agree";
sap.Location = "Location";
sap.Acro6Layers = true;
sap.SignDate = DateTime.Now;
sap.CertificationLevel = level;
}
catch (Exception ex)
{
if (ex.Message == $"The field {certificate.Thumbprint} already exists.")
throw new Exception("Вы уже подписали данный документ");
}
}
public void SetSignatureFieldOptions(X509Certificate2 certificate, PdfSignatureAppearance sap, PdfReader reader,string field, int XPos, int YPos, int width, int height) {
X509CertificateParser parser = new X509CertificateParser();
try
{
Rectangle rectangle = new Rectangle(XPos, YPos, XPos + width, YPos + height);
sap.SetVisibleSignature(rectangle, reader.NumberOfPages, field);
sap.Certificate = parser.ReadCertificate(certificate.RawData);
sap.Reason = "I agree";
sap.Location = "Location";
sap.Acro6Layers = true;
sap.SignDate = DateTime.Now;
}
catch (Exception ex) {
if (ex.Message == $"The field {certificate.Thumbprint} already exists.")
throw new Exception("Вы уже подписали данный документ");
}
}
public void EncryptDocument(X509Certificate2 certificate, PdfSignatureAppearance sap) {
PdfName filterName;
if (certificate.PrivateKey is Gost3410CryptoServiceProvider)
filterName = new PdfName("CryptoPro#20PDF");
else
filterName = PdfName.ADOBE_PPKLITE;
PdfSignature dic = new PdfSignature(filterName, PdfName.ADBE_PKCS7_DETACHED);
dic.Date = new PdfDate(sap.SignDate);
dic.Name = certificate.GetNameInfo(X509NameType.SimpleName, false);
if (sap.Reason != null)
dic.Reason = sap.Reason;
if (sap.Location != null)
dic.Location = sap.Location;
sap.CryptoDictionary = dic;
int intCSize = 4000;
Dictionary<PdfName, int> hashtable = new Dictionary<PdfName, int>();
hashtable[PdfName.CONTENTS] = intCSize * 2 + 2;
sap.PreClose(hashtable);
Stream s = sap.GetRangeStream();
MemoryStream ss = new MemoryStream();
int read = 0;
byte[] buff = new byte[8192];
while ((read = s.Read(buff, 0, 8192)) > 0)
{
ss.Write(buff, 0, read);
}
ContentInfo contentInfo = new ContentInfo(ss.ToArray());
SignedCms signedCms = new SignedCms(contentInfo, true);
CmsSigner cmsSigner = new CmsSigner(certificate);
signedCms.ComputeSignature(cmsSigner, false);
byte[] pk = signedCms.Encode();
byte[] outc = new byte[intCSize];
PdfDictionary dic2 = new PdfDictionary();
Array.Copy(pk, 0, outc, 0, pk.Length);
dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));
sap.Close(dic2);
}
The Change
The most important part of your screenshot
is the text "1 Page(s) Modified" between the signatures on the signature panel. This tells us that you do other changes than merely adding and filling signature fields. Inspecting the file itself one quickly recognizes the change:
In the original sample.pdf
there is just a single content stream.
In sample_signed.pdf with one signature
there are three content streams, the original one enveloped by the new ones.
In sample_signed_signed.pdf with two signatures
there are five content streams, the former three enveloped by two new ones.
So in each signing pass you change the page content. As you can read in this answer, changes to the page content of signed documents are always disallowed. It doesn't even help that the contents of the added streams are trivial, each stream added in front contains:
q
and each stream added at the end contains
Q
q
Q
i.e. only some saving and restoring the graphics state happens.
The Cause
The changes described above are typical preparation steps done by the PdfStamper method GetOverContent, wrapping the original content in a q ... Q (save & restore graphics state) envelope to prevent changes there to influence additions in the OverContent and starting a new block also enveloped in such an envelope. That the latter block remained empty, indicates that the OverContent has not been edited.
I don't find such a call in the code you posted, but in your code the method SetStampCoordinates is missing. Do you probably call GetOverContent for the PdfStamper argument in that method?

How do i use iText to have a landscaped PDF on half of a A4 back to portrait and full size on A4

I have a landscaped form lay on a top half of A4 page, I want it to be rotated and enlarge to a portrait layout size fill up the A4 then saved before it is faxed out. Otherwise, the fax service program will fax it out with only partial info. Here is my attempt, result is the same as the input pdf. This is my first day on programming using iText, all the google not getting me what I want. Please let me know if you can help. Thanks,
public class CopeALandscapePdfFiletoPortraitPdfFile {
//public static final String SRC = "resources/pdfs/landscapeForm.pdf";
public static final String SRC = "resources/pdfs/potraitForm.pdf";
public static final String DEST = "results/stamper/portraitFormAfterCopy.pdf";
public static void main(String[] args) throws IOException, DocumentException
{
copyPdf();
}
private static void copyPdf() throws IOException, DocumentException
{
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(SRC);
document.newPage();
int n = reader.getNumberOfPages();
PdfDictionary page;
PdfNumber rotate;
for (int p = 1; p <= n; p++) {
page = reader.getPageN(p);
rotate = page.getAsNumber(PdfName.ROTATE);
if (rotate == null) {
page.put(PdfName.ROTATE, new PdfNumber(90));
} else {
page.put(PdfName.ROTATE, new PdfNumber((rotate.intValue() + 90) % 360));
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(DEST));
stamper.close();
PdfImportedPage ipage = writer.getImportedPage(stamper.getReader(), 1);
cb.addTemplate(ipage, 0, 0);
document.close();
}
}
As you want to enlarge the PDF anyways, I would put enlarging and rotating into one afine transformation. Thus:
PdfReader reader = new PdfReader(SOURCE);
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, RESULT);
document.open();
double sqrt2 = Math.sqrt(2);
Rectangle pageSize = reader.getPageSize(1);
PdfImportedPage importedPage = writer.getImportedPage(reader, 1);
writer.getDirectContent().addTemplate(importedPage, 0, sqrt2, -sqrt2, 0, pageSize.getTop() * sqrt2, -pageSize.getLeft() * sqrt2);
document.close();
(EnlargePagePart.java)
E.g. for this page
it generates

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