2010-11-08 173 views
9

我想將頁面添加到包含簡單文本的現有PDF文檔。使用iTextSharp將頁面添加到PDF文檔

我曾嘗試下面的代碼,我發現在互聯網上,但到目前爲止,我還沒有得到它的工作:

PdfReader reader = new PdfReader("1.pdf"); 
Document document = new Document(reader.GetPageSize(1)); 
PdfCopy copier = new PdfCopy(doc, new FileStream("2.pdf", FileMode.Create)); 

for (int pageCounter = 1; pageCounter < reader.NumberOfPages + 1; pageCounter++) 
{ 
    //byte[] page = reader.GetPageContent(pageCounter); 
    copier.AddPage(copier.GetImportedPage(reader, pageCounter)); 
} 

copier.NewPage(); 
copier.Add(new Paragraph("This is added text")); 

document.Close(); 
reader.Close(); 

請讓我知道如何做到這一點嗎?

回答

19
private static string AddCommentsToFile(string fileName, string userComments) 
    { 
     string outputFileName = Path.GetTempFileName(); 
     //Step 1: Create a Docuement-Object 
     Document document = new Document(); 
     try 
     { 
      //Step 2: we create a writer that listens to the document 
      PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create)); 

      //Step 3: Open the document 
      document.Open(); 

      PdfContentByte cb = writer.DirectContent; 

      //The current file path 
      string filename = fileName; 

      // we create a reader for the document 
      PdfReader reader = new PdfReader(filename); 

      for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++) 
      { 
       document.SetPageSize(reader.GetPageSizeWithRotation(1)); 
       document.NewPage(); 

       //Insert to Destination on the first page 
       if (pageNumber == 1) 
       { 
        Chunk fileRef = new Chunk(" "); 
        fileRef.SetLocalDestination(filename); 
        document.Add(fileRef); 
       } 

       PdfImportedPage page = writer.GetImportedPage(reader, pageNumber); 
       int rotation = reader.GetPageRotation(pageNumber); 
       if (rotation == 90 || rotation == 270) 
       { 
        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height); 
       } 
       else 
       { 
        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); 
       } 
      } 

      // Add a new page to the pdf file 
      document.NewPage(); 

      Paragraph paragraph = new Paragraph(); 
      Font titleFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA 
             , 15 
             , iTextSharp.text.Font.BOLD 
             , BaseColor.BLACK 
       ); 
      Chunk titleChunk = new Chunk("Comments", titleFont); 
      paragraph.Add(titleChunk); 
      document.Add(paragraph); 

      paragraph = new Paragraph(); 
      Font textFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA 
            , 12 
            , iTextSharp.text.Font.NORMAL 
            , BaseColor.BLACK 
       ); 
      Chunk textChunk = new Chunk(userComments, textFont); 
      paragraph.Add(textChunk); 

      document.Add(paragraph); 
     } 
     catch (Exception e) 
     { 
      throw e; 
     } 
     finally 
     { 
      document.Close(); 
     } 
     return outputFileName; 
    } 
+0

你好,雖然我使用「document.NewPage();」方法來創建新頁面,它會將我的內容與標題重疊。那麼如何在添加新頁面時避免與標題重疊? 請幫忙。謝謝 – Herin 2016-02-17 05:17:10

2

您不能使用PdfCopy來添加頁面。你需要創建一個新的pdf並添加它如果你需要這樣做(PdfCopy是最好的合併pdf)。

我添加了一個例子,如何添加頁腳太:

PdfReader reader = new PdfReader("1.pdf"); 
Document document = new Document(reader.GetPageSize(1)); 
PdfCopy copier = new PdfCopy(doc, new FileStream("2.pdf", FileMode.Create)); 

for (int pageCounter = 1; pageCounter < reader.NumberOfPages + 1; pageCounter++) 
{ 
    // get page 
    PdfImportedPage page = copier.GetImportedPage(reader, pageCounter) 
    // add content to imported page 
    PageStamp ps = pdfCopy.CreatePageStamp(page); 
    PdfContentByte cb = ps.GetOverContent(); 
    // set color 
    cb.SetColorFill(BaseColor.BLACK); 
    // get font 
    BaseFont baseFont = BaseFont.CreateFont(string.Format("{0}\\Fonts\\arialuni.ttf", Environment.GetEnvironmentVariable("windir"), BaseFont.CP1252, BaseFont.NOT_EMBEDDED); 
    cb.SetFontAndSize(baseFont, 12); 
    cb.BeginText(); 
    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, printLangString, 100f, 40f, 0f); 
    cb.EndText(); 
    // Accept changes      
    ps.AlterContents(); 
    // add page 
    copier.AddPage(page); 
} 

using (var ms = new MemoryStream()) 
{ 
    Document doc = new Document(PageSize.A4); 
    PdfWriter writer = PdfWriter.GetInstance(doc, ms); 
    writer.CloseStream = false; 
    doc.Open(); 
    doc.NewPage(); 
    doc.Add(new Paragraph(error, fontRed)); 
    doc.Close(); 
    writer.Close(); 
    ms.Seek(0, SeekOrigin.Begin); 
    PdfReader rd = new PdfReader(ms); 
    for (int pageCounter = 1; pageCounter < reader.NumberOfPages + 1; pageCounter++) 
    { 
     copier.AddPage(copier.GetImportedPage(rd, pageCounter)); 
    } 
    rd.Close(); 
} 

document.Close(); 
reader.Close(); 
3

試試這個代碼:它增加了與現有的PDF中新的一頁,水印文字加入到最後一頁。

private string AddWaterMarkPageToFile(string fileName, string userComments) 
     { 
      string outputFileName = Path.GetTempFileName() + ".pdf"; 
      //Step 1: Create a Docuement-Object 
      Document document = new Document(); 
      try 
      { 
       //Step 2: we create a writer that listens to the document 
       PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create)); 

       //Step 3: Open the document 
       document.Open(); 

       PdfContentByte cb = writer.DirectContent; 

       //The current file path 
       string filename = fileName; 

       // we create a reader for the document 
       PdfReader reader = new PdfReader(filename); 

       for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++) 
       { 
        document.SetPageSize(reader.GetPageSizeWithRotation(1)); 
        document.NewPage(); 

        //Insert to Destination on the first page 
        if (pageNumber == 1) 
        { 
         Chunk fileRef = new Chunk(" "); 
         fileRef.SetLocalDestination(filename); 
         document.Add(fileRef); 
        } 

        PdfImportedPage page = writer.GetImportedPage(reader, pageNumber); 
        int rotation = reader.GetPageRotation(pageNumber); 
        if (rotation == 90 || rotation == 270) 
        { 
         cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height); 
        } 
        else 
        { 
         cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); 
        } 
       } 

       // Add a new page to the pdf file 
       document.NewPage(); 

       float fontSize = 80; 
       float xPosition = iTextSharp.text.PageSize.A4.Width/2; 
       float yPosition = (iTextSharp.text.PageSize.A4.Height - 140f)/2; 
       float angle = 45; 

       PdfContentByte under = writer.DirectContentUnder; 
       BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); 
       under.BeginText(); 
       under.SetColorFill(BaseColor.LIGHT_GRAY); 
       under.SetFontAndSize(baseFont, fontSize); 
       under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, userComments, xPosition, yPosition, angle); 
       under.EndText(); 

      } 
      catch (Exception e) 
      { 
       throw e; 
      } 
      finally 
      { 
       document.Close(); 
      } 
      return outputFileName; 
     } 
相關問題