c# - 编辑现有 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");
}
任何帮助将不胜感激。:)
解决方案
在关闭文档之前更改内存流的位置:
ms.Position = 0;
document.Close();
由于结果流中 pdf 的预告片是在文档关闭期间写入的,因此您更改流位置会导致 pdf 预告片被写入 pdf 标头,并且此后的流位置不在开头。
相反,首先关闭文档和阅读器(作者通过关闭文档隐式关闭)然后重置流位置:
document.Close();
reader.Close();
ms.Position = 0;
return File(ms, "application/pdf","test.pdf");
推荐阅读
- linux - 如何在我的 shell 脚本中包含 html?执行 shell 脚本时可以得到 html 格式的输出吗?
- node.js - 找不到模块'puppeteer'
- java - 如何在第 n 次出现分隔符之前进行子字符串化?
- php - 使用 .htaccess 从 URL 重写 PHP 变量
- python - python-产生并引发异常
- java - org.springframework.data.mapping.model.MappingInstantiationException:无法用新的布尔字段实例化对象
- twig - Twig if 语句为假
- python - Python 尝试除了不使用 np.arccos
- regex - 加快正则表达式匹配
- r - dplyr 计数事件,如果它没有发生