2010-02-09 32 views
18

¿Cuál es la forma óptima de combinar 2 archivos PDF con ITextSharp en C#? Estoy usando ASP.NET/.NET3.5.Fusionando archivos PDF con ITextSharp

+1

He usado código basado en el siguiente artículo con éxito: [Simple .NET fusión del pdf] (http://www.codeproject.com /KB/files/SimplePdfMerger.aspx) –

Respuesta

27
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(); 
      }); 
     } 
    } 
+0

¿Cómo puedo usar esta función? Supongamos que tiene un pdf generado y lo agrega a un archivo físico en PDF. –

+2

Tenga en cuenta que esta respuesta es incorrecta. Descarta toda la interactividad y puede resultar en archivos inflados si los diferentes archivos PDF contienen recursos idénticos. La única respuesta correcta es una respuesta que usa 'PdfSmartCopy' que es otra clase que está disponible en iTextSharp. –

+0

También echaré un vistazo a esta respuesta: https://stackoverflow.com/questions/38339151/c-sharp-itextsharp-merge-multiple-pdf-via-byte-array –

1

La última respuesta funciona si no desea eliminar los archivos originales. En mi caso, quiero eliminar y cuando lo intenté recibí una excepción. Mi solución es:

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; 
     } 

He copiado el código de Original Code

+0

Leve modificaciones para manejar la rotación de páginas, etc., pero aparte de eso, reemplazó fácilmente el código en mi proyecto que estaba bloqueando archivos .. – Ads