Reputation: 5729
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
Upvotes: 2
Views: 8417
Reputation: 21689
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
Upvotes: 7
Reputation: 51
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()
.
Upvotes: 4