简体   繁体   English

Itextsharp PDF 损坏

[英]Itextsharp PDF getting Corrupted

I am working on this feature which takes a pdf from a database and signs the PDF with an image of the signature which needs to be retrieved from the database.我正在研究这个功能,它从数据库中获取 pdf 并使用需要从数据库中检索的签名图像对 PDF 进行签名。 I am using iTextSharp for this, but somehow it is not working and is corrupting my PDF in the database.我为此使用iTextSharp ,但不知何故它不起作用并且正在破坏我在数据库中的 PDF。

This is the code of my controller这是我的控制器的代码

public ActionResult Approve(int? id)
{
    ApplicationUser users = db.Users.Find(User.Identity.GetUserId());
    Reports reports = db.Reports.Find(id);

    if (reports == null || users == null) return View();

    byte[] content = reports.Content;
    byte[] signature = users.Signature; 

    iTextSharp.text.Image sigImg = iTextSharp.text.Image.GetInstance(signature);

    PdfReader reader = new PdfReader(content);
    using (MemoryStream ms = new MemoryStream())
    {
        PdfStamper stamper = new PdfStamper(reader, ms);

        sigImg.SetAbsolutePosition(0f,0f);

        sigImg.ScalePercent(90.0f); // 100.0f == same size


        //Give some space after the image
        sigImg.SpacingAfter = 1f;
        sigImg.Alignment = Element.ALIGN_BOTTOM;

        PdfContentByte over = stamper.GetOverContent(1);

        over.AddImage(sigImg);

        reports.Content = ms.ToArray();
        content = reports.Content;

        ms.Flush();
        db.SaveChanges();
        if(stamper!= null)
            stamper.Close();
        if(reader!= null)
            reader.Close();

        return File(content, "application/pdf");

        // Clean up

    }
}

What am I doing wrong here?我在这里做错了什么?

You retrieve the contents of the MemoryStream您检索MemoryStream的内容

reports.Content = ms.ToArray();

before you close the PdfStamper在关闭PdfStamper之前

if(stamper!= null)
    stamper.Close();

which means the MemoryStream does not yet contain the complete stamped PDF.这意味着MemoryStream尚未包含完整的加盖 PDF。

Thus, change the order of commands, in particular close the stamper before retrieving the bytes from ms .因此,更改命令的顺序,特别是在从ms检索字节之前关闭stamper

As an aside: Why do you check stamper!= null ?顺便说一句:你为​​什么要检查stamper!= null It obviously cannot be null there...那里显然不能为null ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM