2010-11-25 31 views
8

Estoy intentando utilizar PdfSmartCopy de iTextSharp pero no puedo encontrar ejemplos relevantes en C#.ejemplos de uso iTextSharp PdfCopy

La idea es que tengo un pdf que contiene campos de formulario y los campos agregan 700kb al tamaño del documento pdf. El documento original sin campos de formulario era 100kb. Cualquier otra sugerencia es bienvenida, especialmente o reducir el tamaño del pdf consistentemente.

(I optimizado el PDF generado con Adobe Acrobat, y lo redujo a 44kb. Así que debe haber un fallo en alguna parte.) ¿Hay alguna manera de reducir el tamaño PDF?

Editar: FormFlatenning no ayuda. El archivo de plantilla en pdf solo contiene texto, líneas y tablas, no imágenes.

aquí es mi fragmento de código

 PdfReader reader = new PdfReader(GetTemplateBytes()); 
     pst = new PdfStamper(reader, Response.OutputStream); 
     var acroFields = pst.AcroFields; 

     pst.FormFlattening = true; 
     pst.FreeTextFlattening = true; 

     SetFieldsInternal(acroFields); 

     pst.Close(); 
+1

Su título de la pregunta menciones PdfSmartCopy, pero su fuente no. –

+1

Estoy pidiendo el código fuente, no proporcionándolo. –

Respuesta

7

Aquí hay un ejemplo de 2008 VB.Net de usar ITextSharp PDFCopy para copiar múltiples archivos PDF en 1 archivo PDF de varias páginas. Esto copiará todo, excepto los enlaces subyacentes. Parece copiar todas las anotaciones a la perfección, al menos no pude encontrar ninguna que no haya copiado.

Nota: debe tener ITextSharp referenciado en su proyecto.

parámetros de entrada:

fileArray - un array de archivos PDF.

outPutPDF: ruta completa y nombre para generar el documento PDF de varias páginas.

Private Sub BuildMultiPagePDF(ByVal fileArray As String(), ByVal outPutPDF As String) 
    Try 

     Dim reader As iTextSharp.text.pdf.PdfReader = Nothing 
     Dim pageCount As Integer = 0 
     Dim currentPage As Integer = 0 
     Dim pdfDoc As iTextSharp.text.Document = Nothing 
     Dim writer As iTextSharp.text.pdf.PdfCopy = Nothing 
     Dim page As iTextSharp.text.pdf.PdfImportedPage = Nothing 
     Dim currentPDF As Integer = 0 

     If fileArray.Length > 0 Then 

      reader = New iTextSharp.text.pdf.PdfReader(fileArray(currentPDF)) 
      pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1)) 
      writer = New iTextSharp.text.pdf.PdfCopy(pdfDoc, _ 
                New IO.FileStream(outPutPDF, _ 
                IO.FileMode.OpenOrCreate, _ 
                IO.FileAccess.Write)) 

      pageCount = reader.NumberOfPages 

      While currentPDF < fileArray.Length 
       pdfDoc.Open() 

       While currentPage < pageCount 
        currentPage += 1 
        pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(currentPage)) 
        pdfDoc.NewPage() 
        page = writer.GetImportedPage(reader, currentPage) 
        writer.AddPage(page) 
       End While 

       currentPDF += 1 
       If currentPDF < fileArray.Length Then 
        reader = New iTextSharp.text.pdf.PdfReader(fileArray(currentPDF)) 
        pageCount = reader.NumberOfPages 
        currentPage = 0 
       End If 
      End While 

      pdfDoc.Close() 
     Else 
      MessageBox.Show("The input file array is empty. Processing terminated.", _ 
          "INVALID FILE LIST", _ 
          MessageBoxButtons.OK, MessageBoxIcon.Error) 

     End If 

    Catch ex As Exception 
     MessageBox.Show(ex.message) 
    End Try 
End Sub 
+0

En realidad, quiero extraer los datos del archivo PDF usando iTextSharp, el archivo contiene datos en formato de tabla, necesito extraer los datos, por favor dame un ejemplo –

1

llamada reader.removeUnusedObjects() antes de llamar pst.close() ... no hay necesidad de aplanamiento.

Para reducir las cosas un poco más puedes pst.setFullCompression(). YMMV.

EDITAR: Por lo que respecta a los ejemplos, recomiendo obtener iText en acción, segunda edición. Muchos ejemplos de todo tipo de cosas, incluyendo PdfCopy & PdfSmartCopy. Todos los ejemplos de código del libro son available on line.

No gano nada si compra el libro, pero conozco al autor de numerosas interacciones en línea, y lo considero un amigo.

+0

Gracias por la respuesta, logré hacer un archivo pdf más pequeño creando la plantilla usando OpenOffice en lugar de Adobe Acrobat. 80kb frente a 800 kb. –

0

using iTextSharp.text; 
 
using iTextSharp.text.pdf; 
 

 
public void pdfcopyfile() 
 
    { 
 
     string pdfTemplatePath = @"D:\1.pdf"; 
 
     string outputPdfPath = @"D:\44.pdf"; 
 
     iTextSharp.text.pdf.PdfReader reader = null; 
 
     int pageCount = 0; 
 
     int currentPage = 0; 
 
     Document pdfDoc = null; 
 
     PdfCopy writer = null; 
 
     PdfImportedPage page = null; 
 
     reader = new PdfReader(pdfTemplatePath); 
 
     pdfDoc = new Document(reader.GetPageSizeWithRotation(1)); 
 
     writer = new PdfCopy(pdfDoc, new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create)); 
 
     pageCount = reader.NumberOfPages; 
 
     pdfDoc.Open(); 
 
     while (currentPage < pageCount) 
 
     { 
 
      currentPage += 1; 
 
      pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(currentPage)); 
 
      pdfDoc.NewPage(); 
 
      page = writer.GetImportedPage(reader, currentPage); 
 
      writer.AddPage(page); 
 
     } 
 
     reader = new PdfReader(pdfTemplatePath); 
 
     pageCount = reader.NumberOfPages; 
 
     currentPage = 0; 
 
     pdfDoc.Close(); 
 
    }

Cuestiones relacionadas