首页 文章

.net mvc3 iTextSharp如何在内存流中将图像添加到pdf并返回浏览器

提问于
浏览
0

我有一个.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文档正被加载到“file”变量中 . 我还验证了MemoryStream“ms”的长度与byte []“file”的长度相同 .

1 回答

  • 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上的其他几个答案中进行了调整

相关问题