我正在尝试使用OpenFileDialog()
中的iTextSharp
将C#
的一系列图片转换为一张PDF。这是我正在运行的。当我选择文件时,我收到错误:"System.NotSupportedException: 'Stream does not support reading.'"
就行:
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());
}
}
}
答案 0 :(得分:1)
尝试下面的代码,我已经将doc
的开启和关闭移到了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();
}