首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用iTextSharp将多幅图像转换为PDF

使用iTextSharp将多幅图像转换为PDF
EN

Stack Overflow用户
提问于 2018-05-17 12:48:20
回答 1查看 3K关注 0票数 0

我正在尝试转换一系列的图像从OpenFileDialog()到一个PDF使用C#中的iTextSharp。这就是我正在运行的。当我选择文件时,我得到错误:"System.NotSupportedException: 'Stream does not support reading.'"

在线上:

代码语言:javascript
复制
var image = iTextSharp.text.Image.GetInstance(imageStream);

我想知道这个错误意味着什么,或者我可以修复什么来解决这个问题。谢谢。

代码语言:javascript
复制
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();
                    }


                }
            }


        }
    }
}
}

下面是主要代码:

代码语言:javascript
复制
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());
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-05-17 13:21:01

尝试下面的代码,我已经将doc的开始和结束移到了foreach循环之外。调用doc.Close()会关闭父文件流,因此只有在添加完所有图像后才调用doc.Close()非常重要。

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50383513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档