[英]Convert Tif document to PDF with PdfSharp
我正在使用WinForms。 在我的表單中,我有一個顯示tif圖像文檔的圖片框。 我將PdfSharp用作將tif文檔轉換為pdf文檔的參考之一。 好消息是我可以轉換圖片框中當前顯示的tif頁面之一。
問題是,當我擁有一頁以上的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);
}
}
[編輯]添加了完整的工作代碼...帶有硬編碼的路徑。
try
{
string destinaton = @"C:\Temp\Junk\new_PDF_TIF_Document.pdf";
Image MyImage = Image.FromFile(@"C:\Temp\Junk\Sample tif document 5 pages.tiff");
PdfDocument doc = new PdfDocument();
for (int PageIndex = 0; PageIndex < MyImage.GetFrameCount(FrameDimension.Page); PageIndex++)
{
MyImage.SelectActiveFrame(FrameDimension.Page, PageIndex);
XImage img = XImage.FromGdiPlusImage(MyImage);
var page = new PdfPage();
if (img.Width > img.Height)
{
page.Orientation = PageOrientation.Landscape;
}
else
{
page.Orientation = PageOrientation.Portrait;
}
doc.Pages.Add(page);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0);
}
doc.Save(destinaton);
doc.Close();
MyImage.Dispose();
MessageBox.Show("File saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
自從我使用PdfSharp已經有一段時間了,但是您應該能夠在圖像上調用GetFrameCount
方法,它將告訴您它有多少頁。
然后,您可以使用SelectActiveFrame
方法選擇哪個頁面處於活動狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.