编辑现有的pdf并使用iTextSharp和MVC发送下载

时间:2017-03-18 21:27:40

标签: c# asp.net-mvc itext

所以我一直在尝试使用iTextSharp来编辑现有的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文件以供下载,但我遇到了一个心理障碍。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

在第

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

只需将FileStream替换为MemoryStream,并在方法结束时从内存流中返回字节数组:

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

您可以使用itextsharp get byte array在Google中轻松找到它。