0
votes

I'm trying to scale the first page of a PDF using iText7 for .NET. The rest of the pages should remain untouched.

The method below works if the PDF contains one page, but if there's multiple pages, the first (supposed to be scaled) page is blank, while the remaining pages is added correctly.

What am I missing here?

public byte[] ScaleFirstPagePdf(byte[] pdf)
{
    using (var inputStream = new MemoryStream(pdf))
    using (var outputStream = new MemoryStream(pdf))
    using (var srcPdf = new PdfDocument(new PdfReader(inputStream)))
    using (var destPdf = new PdfDocument(new PdfWriter(outputStream)))
    {
        for (int pageNum = 1; pageNum <= srcPdf.GetNumberOfPages(); pageNum++)
        {
            var srcPage = srcPdf.GetPage(pageNum);
            var srcPageSize = srcPage.GetPageSizeWithRotation();

            if (pageNum == 1)
            {
                var destPage = destPdf.AddNewPage(new PageSize(srcPageSize));
                var canvas = new PdfCanvas(destPage);

                var transformMatrix = AffineTransform.GetScaleInstance(0.5f, 0.5f);
                canvas.ConcatMatrix(transformMatrix);

                var pageCopy = srcPage.CopyAsFormXObject(destPdf);
                canvas.AddXObject(pageCopy, 0, 0);
            }
            else
            {
                destPdf.AddPage(srcPage.CopyTo(destPdf));
            }
        }

        destPdf.Close();
        srcPdf.Close();

        return outputStream.ToArray();
    }
}
1

1 Answers

1
votes

I couldn't reproduce the blank page issue with this code, but definitely the files that are generated in this way can be problematic.

The issue is that you are sharing a byte buffer between two memory streams - one used for reading and another one for writing, simultaneously.

Simply using another buffer or relying on the default MemoryStream implementation solved the issue for me, and should do so for you as well because there doesn't seem to be anything suspicious about your code apart from the problem I mentioned.

Here is how you should create the output stream:

using (var inputStream = new MemoryStream(pdf))
using (var outputStream = new MemoryStream())

If you still experience issues even after this tweak then the problem is definitely file-specific and I doubt you could get any help without sharing the file.