【问题标题】:.net mvc3 iTextSharp how to add image to pdf in memory stream and return to browser.net mvc3 iTextSharp如何将图像添加到内存流中的pdf并返回浏览器
【发布时间】:2012-07-20 14:46:02
【问题描述】:

我的数据库中存储了一个 .pdf 文件,并且我的数据库中存储了一个签名文件 (.png)。我正在尝试使用 iTextSharp 将签名图像添加到 .pdf 文件中,并将结果显示到浏览器。

这是我的代码:

        byte[] file = Repo.GetDocumentBytes(applicantApplication.ApplicationID, documentID);
        byte[] signatureBytes = Repo.GetSignatureBytes((Guid)applicantApplicationID, signatureID);

        iTextSharp.text.Image signatureImage = iTextSharp.text.Image.GetInstance(signatureBytes);                      
        iTextSharp.text.Document document = new iTextSharp.text.Document(); 

        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(file, 0, file.Length, true, true))
        {
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();

            signatureImage.SetAbsolutePosition(200, 200);
            signatureImage.ScaleAbsolute(200, 50);
            document.Add(signatureImage);

            document.Close();

            return File(ms.GetBuffer(), "application/pdf");
        }

页面加载完毕,有一个带有签名的.pdf,但找不到原始文档。看起来我正在创建一个新的 .pdf 文件并将图像放入其中,而不是编辑旧的 .pdf 文件。

我已验证原始 .pdf 文档正在加载到“文件”变量中。我还验证了 MemoryStream "ms" 的长度与 byte[] "file" 的长度相同。

【问题讨论】:

    标签: asp.net-mvc-3 image itextsharp memorystream


    【解决方案1】:

    我最终在我的存储库中做了这样的事情:

            using (Stream inputPdfStream = new MemoryStream(file, 0, file.Length, true, true))
            using (Stream inputImageStream = new MemoryStream(signatureBytes, 0, signatureBytes.Length, true, true))
            using (MemoryStream outputPdfStream = new MemoryStream())
            {
                var reader = new PdfReader(inputPdfStream);
                var stamper = new PdfStamper(reader, outputPdfStream);
                var cb = stamper.GetOverContent(1);
    
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                image.SetAbsolutePosition(400, 100);
                image.ScaleAbsolute(200, 50);
                cb.AddImage(image);
    
                stamper.Close();
    
                return outputPdfStream.GetBuffer();
           }
    

    我根据 StackOverflow 上的其他一些答案改编了它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-02
      • 2010-12-03
      • 1970-01-01
      • 2016-02-03
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多