2017-03-18 70 views
0

所以我一直在嘗試使用iTextSharp編輯現有的PDF文件。我已經能夠使用下面的代碼來做到這一點。使用iTextSharp和MVC編輯現有的pdf併發送下載

  public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string name, string mID, string dj) 
    { 
     //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"); 

      //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; 
      font.Color = Colors.stringToBaseColor("224,90,71"); 

      //Do Name 
      DrawText(50, 260, pageSize, pbover, name, font); 

      //Do Date 
      font.Size = 16; 
      DrawText(200, 402, pageSize, pbover, dj, font); 

      //Do mID 
      DrawText(180, 422, pageSize, pbover, mID, font); 
     } 
    } 

我想這個集成到MVC應用程序,將將修改後的PDF文件下載,但我已經遇到了一個心理障礙。任何幫助,將不勝感激。

+0

您現在已將編輯的PDF保存到磁盤。你想下一步該做什麼?發送下載是什麼意思? –

+0

我在想的是不是保存文件,而是修改方法使其返回,在此時我可以將它發送給mvc控制器下載。這將節省我將文件保存到磁盤的麻煩。 – Xerc

回答

1

在行

using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create))) 

只需更換FileStreamMemoryStream,並從內存流在方法的最後返回字節數組:

... 
using (var memoryStream = new MemoryStream()) 
using (var stamper = new PdfStamper(reader, memoryStream)) 
{ 
    ... 
    return memoryStream.ToArray(); 
} 

你可以很容易地itextsharp get byte array發現它在谷歌。