2010-10-21 28 views

Respuesta

84

he encontrado una manera de hacerlo (no sé si es el mejor, pero funciona)

string oldFile = "oldFile.pdf"; 
string newFile = "newFile.pdf"; 

// open the reader 
PdfReader reader = new PdfReader(oldFile); 
Rectangle size = reader.GetPageSizeWithRotation(1); 
Document document = new Document(size); 

// open the writer 
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); 
PdfWriter writer = PdfWriter.GetInstance(document, fs); 
document.Open(); 

// the pdf content 
PdfContentByte cb = writer.DirectContent; 

// select the font properties 
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED); 
cb.SetColorFill(BaseColor.DARK_GRAY); 
cb.SetFontAndSize(bf, 8); 

// write the text in the pdf content 
cb.BeginText(); 
string text = "Some random blablablabla..."; 
// put the alignment and coordinates here 
cb.ShowTextAligned(1, text, 520, 640, 0); 
cb.EndText(); 
cb.BeginText(); 
text = "Other random blabla..."; 
// put the alignment and coordinates here 
cb.ShowTextAligned(2, text, 100, 200, 0); 
cb.EndText(); 

// create the new page and add it to the pdf 
PdfImportedPage page = writer.GetImportedPage(reader, 1); 
cb.AddTemplate(page, 0, 0); 

// close the streams and voilá the file should be changed :) 
document.Close(); 
fs.Close(); 
writer.Close(); 
reader.Close(); 

espero que esto puede ser útil para alguien =) (y post aquí cualquier error)

+0

Se ahorra mi trabajo duro, gracias al azar – dev

+6

Algunos blablablabla - como música para mis oídos! – Pinch

+2

my oldfile.pdf contiene 2 páginas, pero newfile.pdf contiene solo la primera página de oldfile.pdf. Entonces, ¿dónde está la segunda página? – Nurlan

10

Esto funcionó para mí, e incluye el uso de OutputStream:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null); 
    Rectangle size = reader.GetPageSizeWithRotation(1); 
    using (Stream outStream = Response.OutputStream) 
    { 
     Document document = new Document(size); 
     PdfWriter writer = PdfWriter.GetInstance(document, outStream); 

     document.Open(); 
     try 
     { 
      PdfContentByte cb = writer.DirectContent; 

      cb.BeginText(); 
      try 
      { 
       cb.SetFontAndSize(BaseFont.CreateFont(), 12); 
       cb.SetTextMatrix(110, 110); 
       cb.ShowText("aaa"); 
      } 
      finally 
      { 
       cb.EndText(); 
      } 

       PdfImportedPage page = writer.GetImportedPage(reader, 1); 
       cb.AddTemplate(page, 0, 0); 

     } 
     finally 
     { 
      document.Close(); 
      writer.Close(); 
      reader.Close(); 
     } 
    } 
+1

El archivo pdf antiguo contiene 2 páginas, pero el nuevo PDF generado contiene solo la primera página del archivo pdf antiguo. Entonces, ¿dónde está la segunda página? – Nurlan

+0

La pieza AddTemplate debe ocuparse de la rotación, si hay una en el documento de origen - consulte [aquí] (http://stackoverflow.com/a/13943059/444469) – Matthieu

+0

En qué biblioteca están "Solicitud" y "Respuesta" "¿localizado? – tmighty

13

Además a las excelentes respuestas anteriores, a continuación se muestra cómo añadir texto a cada página de un documento de varias páginas:

using (var reader = new PdfReader(@"C:\Input.pdf")) 
{ 
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write)) 
    { 
     var document = new Document(reader.GetPageSizeWithRotation(1)); 
     var writer = PdfWriter.GetInstance(document, fileStream); 

     document.Open(); 

     for (var i = 1; i <= reader.NumberOfPages; i++) 
     { 
      document.NewPage(); 

      var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
      var importedPage = writer.GetImportedPage(reader, i); 

      var contentByte = writer.DirectContent; 
      contentByte.BeginText(); 
      contentByte.SetFontAndSize(baseFont, 12); 

      var multiLineString = "Hello,\r\nWorld!".Split('\n'); 

      foreach (var line in multiLineString) 
      { 
      contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0); 
      } 

      contentByte.EndText(); 
      contentByte.AddTemplate(importedPage, 0, 0); 
     } 

     document.Close(); 
     writer.Close(); 
    } 
} 
+0

La pieza AddTemplate debe encargarse de la rotación, si hay una en el documento de origen; consulte [aquí] (http://stackoverflow.com/a/13943059/444469) – Matthieu

+1

¿Qué tipo de referencias está haciendo para eso? – Si8

+1

este realmente maneja varias páginas –

5

Aquí es un método que utiliza estampador y coordenadas absolutas mostraron en los diferentes clientes PDF (Adobe , FoxIt, etc)

public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, Point point) 
    { 
     //variables 
     string pathin = inputPdfPath; 
     string pathout = outputPdfPath; 

     //create PdfReader object to read from the existing document 
     using (PdfReader reader = new PdfReader(pathin)) 
     //create PdfStamper object to write to get the pages from reader 
     using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create))) 
     { 
      //select two pages from the original document 
      reader.SelectPages("1-2"); 

      //gettins the page size in order to substract from the iTextSharp coordinates 
      var pageSize = reader.GetPageSize(1); 

      // PdfContentByte from stamper to add content to the pages over the original content 
      PdfContentByte pbover = stamper.GetOverContent(1); 

      //add content to the page using ColumnText 
      Font font = new Font(); 
      font.Size = 45; 

      //setting up the X and Y coordinates of the document 
      int x = point.X; 
      int y = point.Y; 

      y = (int) (pageSize.Height - y); 

      ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0); 
     } 
    } 
Cuestiones relacionadas