我正在使用WinForms。在我的表单中,我有一个picturebox显示tif图像文档。我使用PdfSharp作为我的引用之一来将tif文档转换为pdf文档。好消息是,我可以转换当前在picturebox中显示的tif页面之一。
问题在于,当我有一个包含多个页面的tif文档时,我无法将它们全部转换为单个Pdf文件。例如,如果我有一个包含5个页面的tif文档图像,则希望按下按钮并将所有这些5个tif页面转换为5个pdf页面。
以下是一个具有5个页面的tif文档进行测试。
链接:http://www.filedropper.com/sampletifdocument5pages 我的代码:
问题在于,当我有一个包含多个页面的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);
}
}
DrawImage
并增加两个参数来指定PDF中图像的大小。这使您能够在可用区域内按原样绘制图像。缩小大型图像以减小最终PDF文件的大小仍然是有意义的。 - I liked the old Stack Overflow