Mostrando las entradas con la etiqueta itextsharp. Mostrar todas las entradas
Mostrando las entradas con la etiqueta itextsharp. Mostrar todas las entradas

viernes, 29 de noviembre de 2019

227. Unir pdfs

En algunas ocasiones necesitamos manipular pdfs como desarrolladores en este caso una de las herramientas que mas nos ayuda es itextsharp, y es la que emplearemos en este caso.

El caso que presento yo tengo pdf, y estos se deben unir en un solo pdf mayor, para ello vamos ha hacer lo siguiente, primero, vamos a agregar la referencia a nuestro proyecto.




Ahora lo que vamos ha hacer es lo siguiente:

1. Vamos a crear un nuevo pdf
2. Vamos a abrir los pdf y a copiar su contenido el nuevo pdf
3. Cerramos el pdf

Así de sencillo.

Les dejo el código para hacer esto

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnirPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> pdf = new List<string>();
            pdf.Add(@"C:\f\A.pdf");
            pdf.Add(@"C:\f\B.pdf");
            UnirPdf(pdf, @"C:\f\C.pdf");
        }

        public static void UnirPdf(List<string> archivos, string salida)
        {
            Document document = new Document();
            using (FileStream newFileStream = new FileStream(salida, FileMode.Create))
            {
                PdfCopy writer = new PdfCopy(document, newFileStream);
                if (writer == null)
                {
                    return;
                }
                document.Open();

                foreach (string archivo in archivos)
                {
                    PdfReader reader = new PdfReader(archivo);
                    reader.ConsolidateNamedDestinations();
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }

                    PRAcroForm form = reader.AcroForm;
                    if (form != null)
                    {
                        writer.CopyDocumentFields(reader);
                    }

                    reader.Close();
                }
                writer.Close();
                document.Close();
            }
        }

    }
}


Felices lineas