文件管理系統中 ,掃描模組將文檔或證件掃描後。為了便於儲存多個圖片,擬將多個圖片產生一個PDF文檔進行儲存。
這裡我們就需要PDF產生工具了。你可以在這裡下載。PDFCreator
主要使用了開源工具ITextSharp產生PDF文檔。
測試介面如下:
選擇圖片,可多選
產生PDF
產生的PDF檔案:
目前只是產生圖片的pdf檔案,至於更進階的應用的探索,以後寫文章再說吧。
其中關鍵代碼PDFCreator如下
using System;using System.Collections.Generic;using System.Text;using System.IO;namespace PDFCreator{ public class PDFCreator { iTextSharp.text.Document pdfdoc; iTextSharp.text.Image pdfImg; iTextSharp.text.pdf.PdfWriter pdfwriter; string tmpFilePath; public PDFCreator() { pdfdoc = new iTextSharp.text.Document(); try { tmpFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\~tmpPdfCreatorFile.pdf"; if (File.Exists(tmpFilePath)) File.Delete(tmpFilePath); pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(tmpFilePath, FileMode.CreateNew)); pdfdoc.Open(); } catch { throw new Exception("此檔案已存在!"); } } public bool AddURIImage(string imageUrl) { try { //pdfdoc.Open(); pdfdoc.NewPage(); //String imageUrl = "http://jenkov.com/images/" + // "20081123-20081123-3E1W7902-small-portrait.jpg"; pdfImg = iTextSharp.text.Image.GetInstance(new Uri(imageUrl)); pdfImg.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN; //pdfImg.SetAbsolutePosition(500f, 650f); pdfdoc.Add(pdfImg); //pdfdoc.Close(); } catch (Exception e) { return false; } return true; } public bool AddImageFromFile(string imageFilePath) { try { pdfdoc.NewPage(); pdfImg = iTextSharp.text.Image.GetInstance(imageFilePath); pdfImg.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN; // pdfImg.SetAbsolutePosition((iTextSharp.text.PageSize.POSTCARD.Width - pdfImg.ScaledWidth) / 2, //(iTextSharp.text.PageSize.POSTCARD.Height - pdfImg.ScaledHeight) / 2); // pdfwriter.DirectContent.AddImage(pdfImg); pdfdoc.Add(pdfImg); //pdfdoc.Close(); } catch (Exception e) { return false; } return true; } public void SaveToFile(string fileName) { //pdfwriter.Close(); //pdfwriter.Dispose(); pdfdoc.Dispose(); File.Copy(tmpFilePath, fileName, true); File.Delete(tmpFilePath); } }}
調用代碼如下:
private void btnCreatePDF_Click(object sender, EventArgs e) { SaveFileDialog sdiag = new SaveFileDialog(); sdiag.Filter = "PDF文檔|*.pdf"; if (sdiag.ShowDialog() == System.Windows.Forms.DialogResult.OK) { PDFCreator creator = new PDFCreator(); foreach (object obj in listBox1.Items) { if (obj == null) continue; string imgFilePath = obj.ToString(); creator.AddImageFromFile(imgFilePath); } // creator.SaveToFile(sdiag.FileName); } }
你可以在這裡下載。PDFCreator