Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging pdf with pdfsharp : exception en the pdfDocument.close()

I would like to create a function with PDFSharp in order to merge some pdf's.

Here is my code

public class PDF_Merge
{
    static string [] strTabPdfFiles;


    public static string SetPdfToMerge(string strPdfFilesInput)
    {
        strTabPdfFiles = strPdfFilesInput.Split(';');
        return "O";
    }

    public static string MergeToPdf(string strPdfFilesOutput)
    {
        try
        {
            PdfDocument objDocumentFinal = new PdfDocument(strPdfFilesOutput);

            foreach (string strDoc in strTabPdfFiles)
            {
                PdfDocument objDocument = PdfReader.Open(strDoc, PdfDocumentOpenMode.Import);

                foreach (PdfPage page in objDocument.Pages)
                {
                    objDocumentFinal.AddPage(page);
                }
                objDocument.Close();----------> Exception : File cannot be modified
            }
            objDocumentFinal.Close();

            objDocumentFinal.Save(strPdfFilesOutput);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }

        return "O";
    }

}

My problem is that on the objDocument.Close() call, i have an exception : "The document cannot be modified".

Anyone could help me about that ?

Great thanks for this lib,

Best regards,

Nixeus

like image 550
Walter Fabio Simoni Avatar asked Jan 23 '26 11:01

Walter Fabio Simoni


2 Answers

PdfDocument.Close should only be called for documents created with a filename or a stream. Close will then automatically save the contents to the PDF file. You must not call Save in this case.

With the sample code in the question, Close must not be called for objDocument because it was not modified and cannot be saved.
It's OK to call Close for objDocumentFinal to save the changes. You should not call Save for objDocumentFinal because this will only save the changes again.

A PDF file opened with PdfDocumentOpenMode.Import is for import only and cannot be modified.
Try PdfDocumentOpenMode.Modify instead.

Look at the Concatenate Documents sample:
http://www.pdfsharp.net/wiki/ConcatenateDocuments-sample.ashx

like image 178
I liked the old Stack Overflow Avatar answered Jan 25 '26 01:01

I liked the old Stack Overflow


I know I am late to the party, but I encountered this issue today.

The close method is trying to save the document, and thus the requirement for .Modify. In this case you don't need objDocument.Close() at all. You can optionally (and probably should?) call objDocument.Dispose().

like image 29
SMB Avatar answered Jan 25 '26 01:01

SMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!