【发布时间】:2016-05-14 12:28:56
【问题描述】:
我正在使用 WinForms。在我的表单中,我有一个显示 tif 图像文档的图片框。我使用 PdfSharp 作为将 tif 文档转换为 pdf 文档的参考资料之一。好消息是我可以转换当前显示在图片框中的 tif 页面之一。
问题是当我有一个超过 1 页的 tif 文档时,我无法将它们全部转换为单个 Pdf 文件。例如,如果我有一个包含 5 页的 tif 文档图像,我想按下一个按钮并将所有这 5 个 tif 页面转换为 5 个 pdf 页面。
这里的测试是一个 5 页的 tif 文档。
链接: http://www.filedropper.com/sampletifdocument5pages
我的代码:
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
private string srcFile, destFile;
bool success = false;
private void Open_btn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open Image";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(dlg.FileName);
lbl_SrcFile.Text = dlg.FileName;
}
dlg.Dispose();
}
private void Save_btn_Click(object sender, EventArgs e)
{
SaveImageToPDF();
}
private void SaveImageToPDF()
{
try
{
string source = lbl_SrcFile.Text;
string savedfile = @"C:\image\Temporary.tif";
pictureBox1.Image.Save(savedfile);
source = savedfile;
string destinaton = @"C:\image\new_PDF_TIF_Document.pdf";
PdfDocument doc = new PdfDocument();
var page = new PdfPage();
XImage img = XImage.FromFile(source);
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[0]); xgr.DrawImage(img, 0, 0);
doc.Save(destinaton);
doc.Close();
img.Dispose(); //dispose img in order to free the tmp file for deletion (Make sure the PDF file is closed thats being used)
success = true;
MessageBox.Show(" File saved successfully! \n\nLocation: C:\\image\\New PDF Document.pdf", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(destinaton);
File.Delete(savedfile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
【问题讨论】:
标签: c# .net image winforms pdf