Skip to content

Merge Docs from Bytes #311

@Kylar182

Description

@Kylar182

Resources

Examples proved in previous doc site used to work and match this method, new doc site does not have this example.

Reporting an Issue Here

Expected Behavior

Combined PDFs from Memory Stream output a concatenated / merged file.

Actual Behavior

Using this method, I get the a repeat of the first doc for every page in outputDoc. The imported files are stamped and flattened docs from memory streams. The imported files output correctly individually (although a much larger file size for some reason). This seems to be all versions 6 and above. I've tried variations of this method with doc.Pages[i].Clone(), etc. with variations in success.

    /// <summary>
    /// Merges multiple pdfs into a single document
    /// </summary>
    /// <param name="files">list of pdf documents as byte arrays</param>
    /// <returns>byte array of the combined pdf</returns>
    /// <remarks>Flattening will not work after merging</remarks>
    public static byte[] MergePdfs(IEnumerable<byte[]> files)
    {
        byte[] merged;
        PdfDocument outputDoc = new PdfDocument();

        foreach (byte[] file in files)
        {
            using (MemoryStream output = new MemoryStream(file, 0, file.Length))
            {
                using (PdfDocument doc = PdfReader.Open(output, PdfDocumentOpenMode.Import))
                {
                    outputDoc.Version = doc.Version;

                    for (int i = 0; i < doc.PageCount; i++)
                    {
                        PdfPage page = doc.Pages[i];
                        page.Size = PageSize.Letter;
                        outputDoc.AddPage(page);
                    }
                }
            }
        }

        using (MemoryStream output = new MemoryStream())
        {
            outputDoc.Save(output, false);

            output.Seek(0, SeekOrigin.Begin);
            merged = output.ToArray();

            try
            {
                outputDoc.Close();
            }
            catch (Exception) { }
        }

        return merged;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    forumPlease use Discussions or the Support forum to ask Support questions - https://forum.pdfsharp.net/support

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions