C# 使用iTextSharp将多个图像转换为PDF
我正在尝试使用C语言中的iTextSharp将从OpenFileDialog拍摄的一系列图像转换为一个PDF。选择文件时会出现错误:System.NotSupportedException:“流不支持读取。” 在线:C# 使用iTextSharp将多个图像转换为PDF,c#,file,pdf,stream,itext,C#,File,Pdf,Stream,Itext,我正在尝试使用C语言中的iTextSharp将从OpenFileDialog拍摄的一系列图像转换为一个PDF。选择文件时会出现错误:System.NotSupportedException:“流不支持读取。” 在线: var image = iTextSharp.text.Image.GetInstance(imageStream); 我想知道这个错误意味着什么,或者我可以修复什么来解决这个问题。谢谢 namespace WindowsFormsApp2 { public partial c
var image = iTextSharp.text.Image.GetInstance(imageStream);
我想知道这个错误意味着什么,或者我可以修复什么来解决这个问题。谢谢
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private OpenFileDialog ofd = new OpenFileDialog { Multiselect = true, Filter = "Image files | * .jpg;*.jpeg;*.png;" };
// Open file button
private void button1_Click(object sender, EventArgs e)
{
// Run code only if a file is selected
if (ofd.ShowDialog() == DialogResult.OK)
{
Document doc = new Document();
using (var stream = new FileStream("test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
foreach (String file in ofd.SafeFileNames)
{
using (var imageStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
PdfWriter.GetInstance(doc, stream);
doc.Open();
var image = iTextSharp.text.Image.GetInstance(imageStream);
doc.Add(image);
doc.Close();
}
}
}
}
}
}
}
以下是主要代码:
namespace WindowsFormsApp2
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
尝试下面的代码,我已经将文档的打开和关闭移到了foreach循环之外。调用doc.Close会关闭父文件流,因此在添加所有图像后,只调用doc.Close很重要
using (var stream = File.Create("test.pdf"))
using (var doc = new Document())
using (var pdfWriter = PdfWriter.GetInstance(doc, stream))
{
doc.Open();
foreach (var file in ofd.SafeFileNames)
{
using (var imageStream = File.OpenRead(file))
{
var image = Image.GetInstance(imageStream);
doc.Add(image);
}
}
doc.Close();
}
您是否也可以添加main方法-此处的入口点只是一个猜测,但可能是因为var imageStream=new FileStreamfile,FileMode.Create会覆盖图像文件?我想应该是文件模式。Open@Prany我添加了主代码。@Hack我添加了新行以反映这一点。现在我遇到一个关于“无法访问已关闭的文件”的错误。@John,与其在foreach循环中打开和关闭文档,不如打开文档,添加所有图像,然后关闭它。该错误的原因是调用doc.Close关闭流到test.pdf。我正在获取System.IndexOutOfRangeException:“索引超出了数组的边界。”当第一次运行和循环时使用此代码时。@John,你能发布堆栈跟踪吗?我投了赞成票,因为这肯定解决了一个问题。至于索引超出了数组错误的范围:如果按字面意思使用此代码,则此错误可能是由特定图像引起的。为了重现问题,我们需要特定的图像。请注意,一些图像问题多年来已得到修复。您仍在使用不再存在的iTextSharp;今天,我们讨论.NET的iText。您正在使用iText版本5或更早版本;今天是第7版。也许你报告的问题很久以前就解决了。