Pregunta

I have a method, which takes in the following:

  • Byte array, which is a PDF file
  • A "from" size
  • A "to" size

The idea is it transforms a PDF file with a specific size, to another size. I want to return a byte array, and want to keep the whole thing in memory.

I create the PdfWriter using a memorystream in the constructor (outPDF), and then does my conversion. After, I want to say outBytes = outPDF.ToArray(); .

I tried putting this code in three places, see place A, B and C in the code. In place A, the length of the memorystream is only 255, which doesn't work. My guess is the doc.Close() has to run first. In place B and C, the stream is closed, and cannot be accessed.

My question is therefore: How to get a byte array from PdfWriter, writing to a memorystream in iTextSharp

My code:

public static byte[] ConvertPdfSize(byte[] inPDF, LetterSize fromSize, LetterSize toSize)
        {
            if (fromSize != LetterSize.A4 || toSize != LetterSize.Letter)
            {
                throw new ArgumentException("Function only supports from size A4 to size letter");
            }

            MemoryStream outPDF = new MemoryStream();
            byte[] outBytes;
            using (PdfReader pdfr = new PdfReader(inPDF))
            {
                using (Document doc = new Document(PageSize.LETTER))
                {
                    Document.Compress = true;

                    PdfWriter writer = PdfWriter.GetInstance(doc, outPDF);
                    doc.Open();

                    PdfContentByte cb = writer.DirectContent;

                    PdfImportedPage page;

                    for (int i = 1; i < pdfr.NumberOfPages + 1; i++)
                    {
                        page = writer.GetImportedPage(pdfr, i);
                        cb.AddTemplate(page, PageSize.LETTER.Width / pdfr.GetPageSize(i).Width, 0, 0, PageSize.LETTER.Height / pdfr.GetPageSize(i).Height, 0, 0);
                        doc.NewPage();
                    }

                    // place A
                    doc.Close();
                    // place B

                }
                pdfr.Close();
                // place C
            }

            return new byte[0];
        }
¿Fue útil?

Solución

Just return your bytes after all of the iTextSharp stuff is done but before discarding the MemoryStream

using(MemoryStream outPDF = new MemoryStream())
{
    using (PdfReader pdfr = new PdfReader(inPDF))
    {
        using (Document doc = new Document(PageSize.LETTER))
        {
            //...
        }
    }

    return outPDF.ToArray();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top