首页 > 解决方案 > 编辑现有 pdf 文件后,ItextSharp 返回损坏的文件

问题描述

我是 itextSharp 的新手。我正在做的只是编辑旧文件,而不是将新文件保存在服务器上,我只想在当时下载它。但不幸的是,在编辑文件并下载后,文件显示消息无法打开文件。它可能已损坏

这是我的代码。

public FileStreamResult export( int ? id)
    {
        string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));


        PdfReader reader = new PdfReader(pathin);
        iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
        Document document = new Document(size);

        // open the writer
        //FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
        var ms = new MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        writer.CloseStream = false;
        document.Open();

        // the pdf content
        PdfContentByte cb = writer.DirectContent;

        // select the font properties
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.SetColorFill(BaseColor.DARK_GRAY);
        cb.SetFontAndSize(bf, 18f);

        // write the text in the pdf content
        cb.BeginText();
        string text = "this is text";
        // put the alignment and coordinates here
        cb.ShowTextAligned(1, text, 500, 500, 0);
        cb.EndText();
        cb.BeginText();
        text = "this is my post";
        // put the alignment and coordinates here
        cb.ShowTextAligned(1, text, 600, 400, 0);
        cb.EndText();

        // create the new page and add it to the pdf
        PdfImportedPage page = writer.GetImportedPage(reader, 1);
        cb.AddTemplate(page, 0, 0);


        ms.Position = 0;
        document.Close();
        //ms.Close();

        writer.Close();
        reader.Close();


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

任何帮助将不胜感激。:)

标签: c#.netmodel-view-controlleritext

解决方案


在关闭文档之前更改内存流的位置:

    ms.Position = 0;
    document.Close();

由于结果流中 pdf 的预告片是在文档关闭期间写入的,因此您更改流位置会导致 pdf 预告片被写入 pdf 标头,并且此后的流位置不在开头。

相反,首先关闭文档和阅读器(作者通过关闭文档隐式关闭)然后重置流位置:

    document.Close();
    reader.Close();

    ms.Position = 0;
    return File(ms, "application/pdf","test.pdf");

推荐阅读