Scaling PDF with PDFSmartcopy ?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Scaling PDF with PDFSmartcopy ?

Chaitanyag
Hi,

I use the below code to scale the PDF to LETTER size using PDFWriter object.

But it is found that the annotations and other objects are being left behind if we use PDFWriter object, instead if PDFSmartcopy / PDFCopy object is used the annotations will be copied as well.

Can someone help with the process of using PDFSmartcopy to scale down the PDF files.

With thanks,
Chaitanya

public static void ScalePDF(string inPDF)
        {
            try
            {
                PdfReader reader = new PdfReader(new MemoryStream(File.ReadAllBytes(inPDF)));
                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
                var ms = new MemoryStream();
                var writer = PdfWriter.GetInstance(document, ms);
                document.Open();
                var cb = writer.DirectContent;
                pdfPageCount = reader.NumberOfPages;

                for (var pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
                {
                    var page = writer.GetImportedPage(reader, pageNumber);
                    document.SetPageSize(iTextSharp.text.PageSize.LETTER);
                    document.NewPage();

                    var widthFactor = document.PageSize.Width / page.Width;
                    var heightFactor = document.PageSize.Height / page.Height;
                    var factor = Math.Min(widthFactor, heightFactor);

                    var offsetX = (document.PageSize.Width - (page.Width * factor)) / 2;
                    var offsetY = (document.PageSize.Height - (page.Height * factor)) / 2;

                    int rotation = reader.GetPageRotation(pageNumber);
                    if (rotation == 0)
                        cb.AddTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
                    else
                    {
                        var pageWidth = reader.GetPageSizeWithRotation(pageNumber).Width;
                        var pageHeight = reader.GetPageSizeWithRotation(pageNumber).Height;

                        if (rotation == 180)
                            cb.AddTemplate(page, -1f, 0, 0, -1f, pageWidth, pageHeight);
                        else if (rotation == 90)
                            cb.AddTemplate(page, 0, -1f, 1f, 0, 0, pageHeight);
                        else if (rotation == 270)
                            cb.AddTemplate(page, 0, 1f, -1f, 0, pageWidth, 0);
                    }
                }
                document.Close();
                File.WriteAllBytes(inPDF.ToUpper().Replace(".PDF", "_RESIZE.PDF"), ms.GetBuffer());                
            }
            catch (Exception ex)
            {
                // log exception
            }
        }
Loading...