【发布时间】:2014-07-06 12:13:06
【问题描述】:
我正在尝试使用 iTextSharp 向现有 PDF 文件添加文本。我一直在阅读很多帖子,包括popular thread here。
我有一些不同:
- 我的 PDF 有 X 页
- 我希望将所有内容都保存在内存中,并且永远不会在我的文件系统中存储文件
所以我尝试修改代码,让它接受一个字节数组并返回一个字节数组。我已经走到这一步了:
- 代码编译运行
- 我的输出字节数组的长度不同于我的输入字节数组
我的问题:
- 当我稍后存储修改后的字节数组并在我的 PDF 阅读器中打开它时,我看不到我添加的文本
我不明白为什么。从我看到的每篇 StackOverflow 帖子中,我都会这样做。使用DirectContent,我使用BeginText 并写一个文本。但是,无论我如何移动位置,我都看不到它。
知道我的代码中缺少什么吗?
public static byte[] WriteIdOnPdf(byte[] inPDF, string str)
{
byte[] finalBytes;
// open the reader
using (PdfReader reader = new PdfReader(inPDF))
{
Rectangle size = reader.GetPageSizeWithRotation(1);
using (Document document = new Document(size))
{
// open the writer
using (MemoryStream ms = new MemoryStream())
{
using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
{
document.Open();
for (var i = 1; i <= reader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(reader, i);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 18);
var multiLineString = "Hello,\r\nWorld!";
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString,100, 200, 0);
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
document.Close();
ms.Close();
writer.Close();
reader.Close();
}
finalBytes = ms.ToArray();
}
}
}
return finalBytes;
}
【问题讨论】:
-
在关闭 writer 之前关闭内存流。但是关闭期间的作者试图向流中写入一些东西。您首先将添加的内容写在目标页面上,然后将原始页面放在其上方。因此,可以覆盖添加。
标签: c# c#-4.0 pdf stream itextsharp