iTextSharp只添加列表<img/>中的一个图像

时间:2017-02-09 12:33:29

标签: c# .net list pdf itext

我想添加List<Image>中的所有图片,但它只会添加最后一张图片。我尝试使用var代替System.Drawing.Image,但它没有帮助。此外,我尝试更改行的顺序,以确保它不是一些逻辑错误,但它也没有帮助。

SaveFileDialog svg = new SaveFileDialog();
svg.ShowDialog();
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(svg.FileName + ".pdf", FileMode.Create));

doc.Open();
foreach (System.Drawing.Image image in images)
{ 
    iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Tiff);

    if (im.Height > im.Width)
    {            
        float percentage = 0.0f;
        percentage = 700 / im.Height;
        im.ScalePercent(percentage * 100);
    }
    else
    {
        float percentage = 0.0f;
        percentage = 540 / im.Width;
        im.ScalePercent(percentage * 100);
    }

    im.Border = iTextSharp.text.Rectangle.BOX;
    im.BorderColor = iTextSharp.text.BaseColor.BLACK;
    im.BorderWidth = 3f;
    doc.Add(im);
    doc.NewPage();
}
doc.Close();

有什么问题? foreach可以在pictureboxes中正常显示这些图片。我不明白为什么它不能与iTextSharp一起使用。

1 个答案:

答案 0 :(得分:0)

您的代码按预期正常工作

要么您没有在右侧文件夹中查看正确的输出pdf文件,要么您的循环中没有不同的图像(前者更可能是基于您所写的内容...)

无论如何,我可以确认您帖子中的代码会生成包含不同图片的页面。

修改

首先尝试设置输出文件路径而不使用文件对话框,然后按照简单的教程查看如何管理对话框的事件处理程序,例如here

    private void button1_Click(object sender, EventArgs e)
    {
        // When user clicks button, show the dialog.
        saveFileDialog1.ShowDialog();
    }

    private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
    {
        // Get file name.
        string name = saveFileDialog1.FileName;
        // Write to the file name selected.
        // ... You can write the text from a TextBox instead of a string literal.
        // insert the code for the pdf here
    }

还尝试将图像保存到磁盘之前(以便稍后再仔细检查),然后从文件中加载它们

            System.Drawing.Image[] images = new System.Drawing.Image[3];
            images[0] = System.Drawing.Image.FromFile(@"\\My Pictures\pic1.bmp");
            images[1] = System.Drawing.Image.FromFile(@"\\My Pictures\pic2.JPG");
            //etc...