ItextSharp编辑现有的pdf文件后返回损坏的文件

时间:2018-11-10 16:03:27

标签: c# .net model-view-controller itext

我是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");
    }

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

1 个答案:

答案 0 :(得分:0)

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

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

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

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

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

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