2012-04-17 29 views
5

Estoy tratando de combinar muchos PDF y para cada PDF quiero agregar un marcador (el nombre del pdf), encontré diferentes técnicas de fusión de PDF pero ninguno de ellos puede agregar solo el marcador anterior, por ej. itextsharp add es un capítulo, luego el marcador para el capítulo, no quiero alterar el pdf.Fusionando archivos pdf con marcadores

+1

Quizás necesite extraer las páginas individuales y volver a unirlas en un único archivo. De esta manera puede marcar la primera página de cada pdf con el marcador – gyurisc

+0

No sé cómo agregar un simplebookmark – XandrUu

Respuesta

13

Usando itextsharp puedes hacerlo. lo hago por el siguiente método ...

MergePdfFiles(string outputPdf, string[] sourcePdfs) 
{ 
     PdfReader reader = null; 
     Document document = new Document(); 
     PdfImportedPage page = null; 
     PdfCopy pdfCpy = null; 
     int n = 0; 
     int totalPages = 0; 
     int page_offset = 0; 
     List<Dictionary<string, object>> bookmarks = new List<Dictionary<string, object>>(); 
     IList<Dictionary<string, object>> tempBookmarks; 
     for (int i = 0; i <= sourcePdfs.GetUpperBound(0); i++) 
       { 
        reader = new PdfReader(sourcePdfs[i]); 
        reader.ConsolidateNamedDestinations(); 
        n = reader.NumberOfPages; 
        tempBookmarks = SimpleBookmark.GetBookmark(reader); 

        if (i == 0) 
        { 
        document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)); 
         pdfCpy = new PdfCopy(document, new FileStream(outputPdf, FileMode.Create)); 
         document.Open(); 
         SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null); 
         page_offset += n; 
         if (tempBookmarks != null) 
          bookmarks.AddRange(tempBookmarks); 
         // MessageBox.Show(n.ToString()); 
         totalPages = n; 
        } 
        else 
        { 
         SimpleBookmark.ShiftPageNumbers(tempBookmarks, page_offset, null); 
         if (tempBookmarks != null) 
          bookmarks.AddRange(tempBookmarks); 

         page_offset += n; 
         totalPages += n; 
        } 

        for (int j = 1; j <= n; j++) 
        { 
         page = pdfCpy.GetImportedPage(reader, j); 
         pdfCpy.AddPage(page); 

        } 
        reader.Close(); 

       } 
      pdfCpy.Outlines = bookmarks; 
      document.Close(); 
    } 
+0

Se ejecutó este código y se combinó el pdf, pero no se agregaron marcadores. Los archivos PDF iniciales deben tener marcadores para mostrar en el pdf final. – Moji

+0

Solo tengo que decir ¡Gracias por este código! He estado navegando por la web durante los últimos días hasta que me encontré con esto en este momento. ¡Gracias de nuevo! – calcazar

+0

bien, después de algún tiempo de búsqueda tropecé con esta pieza de código, ¡funciona perfectamente! – Gelootn

0

Pruebe Docotic.Pdf library para la tarea.

Aquí es un ejemplo de código que hace lo que usted describe:

public static void combineDocumentsWithBookmarks() 
{ 
    string[] names = new string[] { "first.pdf", "second.pdf", "third.pdf" }; 

    using (PdfDocument pdf = new PdfDocument()) 
    { 
     int targetPageIndex = 0; 
     for (int i = 0; i < names.Length; i++) 
     { 
      string currentName = names[i]; 

      if (i == 0) 
       pdf.Open(currentName); 
      else 
       pdf.Append(currentName); 

      pdf.OutlineRoot.AddChild(currentName, targetPageIndex); 
      targetPageIndex = pdf.PageCount; 
     } 

     // setting PageMode will cause PDF viewer to display 
     // bookmarks pane when document is open 
     pdf.PageMode = PdfPageMode.UseOutlines; 
     pdf.Save("output.pdf"); 
    } 
} 

La muestra combina diferentes documentos en un solo PDF y crea marcadores. Cada marcador apunta a la primera página del documento original.

Descargo de responsabilidad: Trabajo para la compañía que desarrolla la biblioteca Docotic.Pdf.

0
public string MergeFiles(string outputPath) 
{ 
    if (string.IsNullOrEmpty(outputPath)) 
     throw new NullReferenceException("Path for output document is null or empty."); 

    using (Document outputDocument = new Document()) 
    { 
     using (PdfCopy pdf = new PdfCopy(outputDocument, new FileStream(outputPath, FileMode.Create))) 
     { 
      outputDocument.Open(); 
      // All bookmarks for output document 
      List<Dictionary<string, object>> bookmarks = new List<Dictionary<string, object>>(); 
      // Bookmarks of the current document 
      IList<Dictionary<string, object>> tempBookmarks; 
      int pageOffset = 0; 

      // Merge documents and add bookmarks 
      foreach (string file in Files) 
      { 
       using (PdfReader reader = new PdfReader(file)) 
       { 
        reader.ConsolidateNamedDestinations(); 
        // Get bookmarks of current document 
        tempBookmarks = SimpleBookmark.GetBookmark(reader); 

        SimpleBookmark.ShiftPageNumbers(tempBookmarks, pageOffset, null); 

        pageOffset += reader.NumberOfPages; 

        if(tempBookmarks != null) 
         // Add bookmarks of current document to all bookmarks 
         bookmarks.AddRange(tempBookmarks); 

        // Add every page of document to output document 
        for (int i = 1; i <= reader.NumberOfPages; i++) 
         pdf.AddPage(pdf.GetImportedPage(reader, i)); 
       } 
      } 

      // Add all bookmarks to output document 
      pdf.Outlines = bookmarks; 
     } 
    } 

    return outputPath; 
} 

optimicé respuesta Md Kamruzzaman de Sarker mediante el uso de un bucle foreach para repasar los archivos PDF y el uso de declaraciones. De esta manera, me parece más limpio, pero todos los créditos van para él.