一开始根据大部分网上的方式使用iTextSharp组件合成PDF,在初始化pdfdocument对象时,提示“未将对象引用设置为对象的实例”。
iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(@"D:\1.pdf", FileMode.Create, FileAccess.ReadWrite));
不知道是否跟iTextSharp版本有关系不,尝试了降低了版本仍然存在该报错。
于是使用了itext7组件进行合成pdf
string[] files = { @"D:\101\1.jpg", @"D:\101\2.jpg" };
using MemoryStream stream = new MemoryStream();
using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(stream)))
{
for (int i = 0; i < files.Length; i++)
{
ImageData imageData = ImageDataFactory.Create(files[i]);
var pageSize = new PageSize(imageData.GetWidth(), imageData.GetHeight());
PdfPage page = pdfDocument.AddNewPage(pageSize);
PdfCanvas canvas = new PdfCanvas(page, true);
canvas.AddImageFittedIntoRectangle(imageData, pageSize, true);
}
}
using FileStream fs = new FileStream(@"D:\101\1.pdf", FileMode.OpenOrCreate);
using BinaryWriter w = new BinaryWriter(fs);
w.Write(stream.ToArray());
文章讲述了在使用iTextSharp组件创建PDF时遇到‘未将对象引用设置为对象的实例’的错误,尝试降低版本无效。然后作者转向使用iText7,成功地合成了包含多张图片的PDF。通过创建PdfDocument,添加页面和图像,最后将内容写入文件。
2465

被折叠的 条评论
为什么被折叠?



