简体   繁体   中英

How to add images to pdf with template and concat of pages

I'm struggling to insert images on a multi-page PDF. To create several pages I'm using PdfConcatenate, and it works. I get to add pages of my template perfectly. The problem starts when I try to add images. It just doesn't load them.

Here's the code that works to add images:

        string pdfTemplate = @"Tools\template.pdf";
        string targetPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), fileName + ".pdf");

        FileStream output = new FileStream(targetPdfPath, FileMode.Create);
        PdfConcatenate pdfConcatenate = new PdfConcatenate(output);

        PdfReader pdfReader = new PdfReader(pdfTemplate);
        MemoryStream memoryStream = getMemoryStream(output);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, output);

        int cardIndex = 1;

        foreach (Registry reg in registries)
        {
            setFields(reg, pdfStamper, cardIndex);

            if (cardIndex == 4)
            {
                pdfConcatenate.AddPages(pdfReader);
                pdfReader = new PdfReader(pdfTemplate);
                pdfStamper = new PdfStamper(pdfReader, output);

                cardIndex = 1;
            }
            else
            {
                cardIndex++;
            }
        }

        //if (cardIndex != 1)
        //    pdfConcatenate.AddPages(pdfReader);

        //make the form no longer editable
        pdfStamper.FormFlattening = true;

        pdfStamper.Close();
        pdfReader.Close();
        //pdfConcatenate.Close();

If use MemoryStream for PdfStamper and uncomment these lines:

//if (cardIndex != 1)
//    pdfConcatenate.AddPages(pdfReader);
//pdfConcatenate.Close();

I get it to add pages, but without images.

Any idea of what is wrong?

SOLUTION: (Thanks to @mkl)

        string pdfTemplate = @"Tools\template.pdf";
        string targetPdfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), fileName + ".pdf");

        FileStream output = new FileStream(targetPdfPath, FileMode.Create);
        PdfConcatenate pdfConcatenate = new PdfConcatenate(output);

        PdfReader pdfReader = new PdfReader(pdfTemplate);
        MemoryStream memoryStream = new MemoryStream();
        PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream);

        int cardIndex = 1;

        foreach (Registry reg in registries)
        {
            setFields(reg, pdfStamper, cardIndex);

            if (cardIndex == 4)
            {
                pdfStamper.FormFlattening = true;
                pdfStamper.Close();
                PdfReader tempReader = new PdfReader(memoryStream.ToArray());

                pdfConcatenate.AddPages(tempReader);

                memoryStream = new MemoryStream();
                pdfReader = new PdfReader(pdfTemplate);
                pdfStamper = new PdfStamper(pdfReader, memoryStream);

                cardIndex = 1;
            }
            else
            {
                cardIndex++;
            }
        }

        if (cardIndex != 1)
        {
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            PdfReader tempReader = new PdfReader(memoryStream.ToArray());

            pdfConcatenate.AddPages(tempReader);

            tempReader.Close();
        }

        pdfStamper.Close();
        pdfReader.Close();
        pdfConcatenate.Close();

The problem most likely is some misconception on how PdfStamper works. You seem to think it somehow manipulates the data in the PdfReader it stamps, and also pages exported from that reader beforehand. This is not the case, a PdfStamper generates a new PDF file (in its output stream) based on the data in the reader but the contents of the reader itself are not updated to also reflect all the changes (the PdfReader object may be touched in the process, though, and not be reusable afterwards). So...

As already mentioned in the comment, you have the PdfConcatenate and an unknown number of PdfStamper instances all writing the same `FileStream' output. As each of these objects creates an independant PDF, you are lucky if one of then wins because then you'll get at least a proper PDF as output. Otherwise you either get some exception or garbage consisting of multiple intermingled PDFs. Thus, make only PdfConcatenate target your output file.

If your actual intent is to repeatedly fill the template fields with the content of 4 cards each time and combine the results, you should not add the pages from the PdfReader of the template to the PdfConcatenate --- the pages in that reader are not filled in! --- but instead have the PdfStamper output to a MemoryStream , fill its fields, flatten its form, close it, open its output in a new PdfReader , and add all the pages in that reader to the PdfConcatenate.

I don't dare to put that into code as I'm predominantly using Java and writing down untested C# code most likely would include multiple errors... ;)

PS: Currently you count on all the PdfReader instances you open to be implicitly closed somewhere. While that is true currently, recent check-ins in the iText SVN repository seem to indicate that these implicit close calls are removed from the code. Thus, please also start explicitly closing PdfReader instances you dont't use anymore. Otherwise you will soon have to deal with memory leaks due to readers closing much too late..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM