Quel est le moyen optimal de fusionner 2 PDF fichiers avec ITextSharp en C #? J'utilise ASP.NET/.NET3.5.
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
});
}
}
La dernière réponse fonctionne si vous ne voulez pas supprimer les fichiers originaux. Dans mon cas, je veux supprimer et quand j'ai essayé, j'ai une exception. Ma solution est:
public static bool MergePDFs(List<String> InFiles, String OutFile)
{
bool merged = true;
try
{
List<PdfReader> readerList = new List<PdfReader>();
foreach (string filePath in InFiles)
{
PdfReader pdfReader = new PdfReader(filePath);
readerList.Add(pdfReader);
}
//Define a new output document and its size, type
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
//Create blank output pdf file and get the stream to write on it.
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OutFile, FileMode.Create));
document.Open();
foreach (PdfReader reader in readerList)
{
PdfReader.unethicalreading = true;
for (int i = 1; i <= reader.NumberOfPages; i++)
{
PdfImportedPage page = writer.GetImportedPage(reader, i);
document.Add(iTextSharp.text.Image.GetInstance(page));
}
}
document.Close();
foreach (PdfReader reader in readerList)
{
reader.Close();
}
}
catch (Exception ex)
{
merged = false;
}
return merged;
}
J'ai copié le code de Code d'origine