2017-07-28 77 views
0

我有一個pdf文件,其中包含一些數據。現在,我想使用這個現有的pdf文件並插入一個表格。然後,我想用另一個文件名保存文件,以便現有的pdf文件保持與以前相同。寫入一個現有的pdf文件,並使用itextsharp將其另存爲一個新文件

注意:現有的pdf文件不是使用iTextSharp創建的。它被隨機下載。我必須像使用模板一樣使用現有的pdf文件。

public void Main(List<string> jobpath) 
{ 

    string oldpath = @"C:\Files\sample_new.pdf"; 
    string newpath = @"C:\Files\sample_new_1.pdf"; 

    PdfReader reader = new PdfReader(oldpath); 
    Rectangle size = reader.GetPageSizeWithRotation(1); 
    Document doc = new Document(size); 

    FileStream fs = new FileStream(newpath, FileMode.Create, FileAccess.Write); 
    PdfWriter writer = PdfWriter.GetInstance(doc, fs); 
    doc.Open(); 

    foreach (var list in jobpath) 
    { 
     cb.BeginText();    
     doc.NewPage(); 
     doc.Open();    

     PdfPTable table = new PdfPTable(1); 
     table.HorizontalAlignment = Element.ALIGN_CENTER; 
     table.TotalWidth = 400f; 
     float[] widths = new float[] { 2f }; 
     table.SetWidths(widths); 
     table.SpacingBefore = 40f; 
     table.SpacingAfter = 30f; 

     PdfPCell cell = new PdfPCell(); 
     cell.Colspan = 3; 
     cell.HorizontalAlignment = 1; 

     table.AddCell(list); 

     doc.Add(table); 

     PdfImportedPage page = writer.GetImportedPage(reader, 1);           
    } 
    doc.Close(); 
} 

通過上面的代碼,我可以添加表格,但舊文件的內容不會被複制到新文件中。

+0

你有什麼試過的?請與我們分享您的代碼。 – Ben

+0

@Ben我已經分享了代碼 – Ksingh

回答

-1

通過以下代碼,我可以將現有PDF的內容添加到新的PDF中。在這個例子中只增加了第一頁。

string oldpath = @"C:\Files\sample_new.pdf"; 
string newpath = @"C:\Files\sample_new_1.pdf"; 

PdfReader reader = new PdfReader(oldpath); 
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1); 
Document doc = new Document(size); 

FileStream fs = new FileStream(newpath, FileMode.Create, FileAccess.Write); 
PdfWriter writer = PdfWriter.GetInstance(doc, fs); 
doc.Open(); 

PdfContentByte cb = writer.DirectContent; 

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

foreach (var list in jobpath) 
{ 
    doc.NewPage(); 
    doc.Open();      

    PdfPTable table = new PdfPTable(1); 
    table.HorizontalAlignment = Element.ALIGN_CENTER; 
    table.TotalWidth = 400f; 
    float[] widths = new float[] { 2f }; 
    table.SetWidths(widths); 
    table.SpacingBefore = 40f; 
    table.SpacingAfter = 30f; 

    PdfPCell cell = new PdfPCell(); 
    cell.Colspan = 3; 
    cell.HorizontalAlignment = 1; 
    table.AddCell(list); 
    doc.Add(table); 
} 
doc.Close(); 
+0

爲什麼要使用'AddTemplate()'添加現有文檔的頁面。這拋棄了原始文檔中的所有交互性。你應該使用'PdfStamper'而不是'InsertPage()'來添加額外的頁面。我暫時對您的答案進行了投票。一旦你修復了它,以便它使用「PdfStamper」,讓我知道,我會刪除倒票(除非有人提供了一個更正確的例子)。 –

相關問題