C#操作PDF总结
C#生成PDF總結
http://www.cnblogs.com/Joetao/articles/2933941.html(一)C#生成PDF總結
(1)iTextSharp控件對iTextSharp研究還可以表格、文字、各種GDI對象,圖片,水印,文字旋轉
(2)aspose的控件
(3)PDF Library這個類庫(只單純是有文字的,表格和文字)http://www.codeproject.com/KB/dotnet/PdfLibrary.aspx?
(4)直接用.net的RDLC report 就可以啦,to PDF效果很好,也可以對付用戶有變數,可以to 其他格式.
(二)iTextSharp生成PDF示列
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO;namespace PdfDemo {/// <summary>/// MainWindow.xaml 的交互邏輯/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}/// <summary>/// 我得第一個Pdf程序/// </summary>private void CreatePdf(){string fileName = string.Empty;Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();dlg.FileName = "我的第一個PDF";dlg.DefaultExt = ".pdf";dlg.Filter = "Text documents (.pdf)|*.pdf";Nullable<bool> result = dlg.ShowDialog();if (result == true){fileName = dlg.FileName;Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));document.Open();iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph("Hello World");document.Add(paragraph);document.Close(); }//end if }/// <summary>/// 設置頁面大小、作者、標題等相關信息設置/// </summary>private void CreatePdfSetInfo(){string fileName = string.Empty;Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();dlg.FileName = "我的第一個PDF";dlg.DefaultExt = ".pdf";dlg.Filter = "Text documents (.pdf)|*.pdf";Nullable<bool> result = dlg.ShowDialog();if (result == true){fileName = dlg.FileName;//設置頁面大小iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);//設置邊界Document document = new Document(pageSize, 36f, 72f, 108f, 180f);PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));// 添加文檔信息document.AddTitle("PDFInfo");document.AddSubject("Demo of PDFInfo");document.AddKeywords("Info, PDF, Demo");document.AddCreator("SetPdfInfoDemo");document.AddAuthor("焦濤");document.Open();// 添加文檔內容for (int i = 0; i < 5; i++){document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!"));} document.Close();}//end if}/// <summary>/// 創建多個Pdf新頁/// </summary>private void CreateNewPdfPage(){string fileName = string.Empty;Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();dlg.FileName = "創建多個Pdf新頁";dlg.DefaultExt = ".pdf";dlg.Filter = "Text documents (.pdf)|*.pdf";Nullable<bool> result = dlg.ShowDialog();if (result == true){fileName = dlg.FileName;Document document = new Document(PageSize.NOTE); PdfWriter writer= PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create)); document.Open();// 第一頁document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1"));document.Add(new iTextSharp.text.Paragraph("PDF1, PDF1, PDF1, PDF1, PDF1")); // 添加新頁面document.NewPage();// 第二頁// 添加第二頁內容document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2"));document.Add(new iTextSharp.text.Paragraph("PDF2, PDF2, PDF2, PDF2, PDF2")); // 添加新頁面document.NewPage();// 第三頁// 添加新內容document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));document.Add(new iTextSharp.text.Paragraph("PDF3, PDF3, PDF3, PDF3, PDF3"));// 重新開始頁面計數document.ResetPageCount();// 新建一頁document.NewPage();// 第四頁// 添加第四頁內容document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));document.Add(new iTextSharp.text.Paragraph("PDF4, PDF4, PDF4, PDF4, PDF4"));document.Close();}//end if}/// <summary>/// 生成圖片pdf頁(pdf中插入圖片)/// </summary>public void ImageDirect(){string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.jpg"; //臨時文件路徑string fileName = string.Empty;Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();dlg.FileName = "我的第一個PDF";dlg.DefaultExt = ".pdf";dlg.Filter = "Text documents (.pdf)|*.pdf";Nullable<bool> result = dlg.ShowDialog();if (result == true){fileName = dlg.FileName;Document document = new Document();PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));document.Open();iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);img.SetAbsolutePosition((PageSize.POSTCARD.Width - img.ScaledWidth) / 2, (PageSize.POSTCARD.Height - img.ScaledHeight) / 2);writer.DirectContent.AddImage(img);iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph("Foobar Film Festival", new iTextSharp.text.Font(Font.FontFamily.HELVETICA, 22f));p.Alignment = Element.ALIGN_CENTER;document.Add(p);document.Close();}//end if}private void ReadPdf(){Console.WriteLine("讀取PDF文檔");try{// 創建一個PdfReader對象PdfReader reader = new PdfReader(@"D:\技術文檔\sj\C#線程參考手冊.pdf");// 獲得文檔頁數int n = reader.NumberOfPages;// 獲得第一頁的大小iTextSharp.text.Rectangle psize = reader.GetPageSize(1);float width = psize.Width;float height = psize.Height;// 創建一個文檔變量Document document = new Document(psize, 50, 50, 50, 50);// 創建該文檔PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:\Read.pdf", FileMode.Create));// 打開文檔document.Open();// 添加內容PdfContentByte cb = writer.DirectContent;int i = 0;int p = 0;Console.WriteLine("一共有 " + n + " 頁.");while (i < n){document.NewPage();p++;i++;PdfImportedPage page1 = writer.GetImportedPage(reader, i);cb.AddTemplate(page1, .5f, 0, 0, .5f, 0, height / 2);Console.WriteLine("處理第 " + i + " 頁");if (i < n){i++;PdfImportedPage page2 = writer.GetImportedPage(reader, i);cb.AddTemplate(page2, .5f, 0, 0, .5f, width / 2, height / 2);Console.WriteLine("處理第 " + i + " 頁");}if (i < n){i++;PdfImportedPage page3 = writer.GetImportedPage(reader, i);cb.AddTemplate(page3, .5f, 0, 0, .5f, 0, 0);Console.WriteLine("處理第 " + i + " 頁");}if (i < n){i++;PdfImportedPage page4 = writer.GetImportedPage(reader, i);cb.AddTemplate(page4, .5f, 0, 0, .5f, width / 2, 0);Console.WriteLine("處理第 " + i + " 頁");}cb.SetRGBColorStroke(255, 0, 0);cb.MoveTo(0, height / 2);cb.LineTo(width, height / 2);cb.Stroke();cb.MoveTo(width / 2, height);cb.LineTo(width / 2, 0);cb.Stroke();BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);cb.BeginText();cb.SetFontAndSize(bf, 14);cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 4) + (n % 4 > 0 ? 1 : 0)), width / 2, 40, 0);cb.EndText();}// 關閉文檔document.Close();}catch (Exception de){Console.Error.WriteLine(de.Message);Console.Error.WriteLine(de.StackTrace);}}/// <summary>/// 創建表格/// </summary>public void CreateFirstTable(){string imagePath = AppDomain.CurrentDomain.BaseDirectory + @"Image\1.pm"; //臨時文件路徑string fileName = string.Empty;Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();dlg.FileName = "我的第一個PDF";dlg.DefaultExt = ".pdf";dlg.Filter = "Text documents (.pdf)|*.pdf";Nullable<bool> result = dlg.ShowDialog();if (result == true){fileName = dlg.FileName;Document document = new Document();PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));document.Open();PdfPTable table = new PdfPTable(3);PdfPCell cell;cell=new PdfPCell(new Phrase("Cell with colspan 3"));cell.Colspan = 3;table.AddCell(cell);cell = new PdfPCell(new Phrase("Cell with rowspan 2"));cell.Rowspan = 2;table.AddCell(cell);table.AddCell("row 1; cell 1");table.AddCell("row 1; cell 2");table.AddCell("row 2; cell 1");table.AddCell("row 2; cell 2");document.Add(table);document.Close();}//end if}private void button1_Click(object sender, RoutedEventArgs e){//CreatePdf(); //CreatePdfPageSize();CreateNewPdfPage();}private void button2_Click(object sender, RoutedEventArgs e){CreateFirstTable();}private void button3_Click(object sender, RoutedEventArgs e){ImageDirect();}private void button4_Click(object sender, RoutedEventArgs e){ReadPdf();} } }
(三)代碼下載
代碼下載
(三)參考鏈接
http://www.cnbeta.com/articles/60484.htm 在線導出PDF的好去處
http://bbs.csdn.net/topics/310095053 PDF導出的討論
http://www.cnblogs.com/EKPK/archive/2009/06/04/1495867.html 用C#制作PDF文件全攻略
http://blog.csdn.net/aasswwe/article/details/7639768
http://blog.sina.com.cn/s/blog_82662ce70100t0s6.html Pdf常見用法
http://www.tuicool.com/articles/nuyAFz HTML生成PDF(c#)
http://stackoverflow.com/questions/tagged/itextsharp itextsharp相關問題?
http://www.itextpdf.com/book/examples.php 官方文檔,雖然是Java版本的但類庫略有不同,在java中一些getFunction和setFunction在C#轉為屬性,可以作為參考文檔。
========
C#讀取PDF ——PDFBox使用
http://blog.csdn.net/LCL_data/article/details/6043898一、下載PDFBox
? ? ? 訪問網址http://sourceforge.net/projects/pdfbox/ (這個絕對是個好網站)
二、引用動態鏈接庫
? ? 解壓縮下載的PDFBox,找到其中的Bin目錄,需要在項目中添加引用的dll文件有:
? ? IKVM.GNU.Classpath.dll
? ? PDFBox-0.7.3.dll
? ? FontBox-0.1.0-dev.dll
? ? IKVM.Runtime.dll
將以上4個文件引用到項目中,在文件中需要引入以下2個命名空間:
? ? using org.pdfbox.pdmodel;
? ? using org.pdfbox.util;
三、API的使用方法
using System.IO; using System.Text; using org.pdfbox.pdmodel; using org.pdfbox.util;namespace PDFReader {class Program{ public static void pdf2txt(FileInfo pdffile, FileInfo txtfile){ PDDocument doc = PDDocument.load(pdffile.FullName); PDFTextStripper pdfStripper = new PDFTextStripper(); string text = pdfStripper.getText(doc); StreamWriter swPdfChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312")); swPdfChange.Write(text); swPdfChange.Close(); }static void Main(string[] args){pdf2txt(new FileInfo(@"C:/Users/Susan/Desktop/完整稿__匆匆那年_九夜茴.pdf"), new FileInfo(@"C:/Users/Susan/Desktop/完整稿__匆匆那年_九夜茴.txt"));}} }
轉化中文是沒有問題的,原因你應該知道。
========
C#使用iTextSharp從PDF文檔獲取內容的方法
http://www.jb51.net/article/73818.htm這篇文章主要介紹了C#使用iTextSharp從PDF文檔獲取內容的方法,涉及C#基于iTextSharp操作pdf文件的相關技巧,需要的朋友可以參考下
本文實例講述了C#使用iTextSharp從PDF文檔獲取內容的方法。具體實現方法如下:
?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; namespace WindowsFormsApplication1 {public partial class Form1 : Form{public Form1(){InitializeComponent();ExtractTextFromPDFPage("c:\sample.pdf", 1);}public void ExtractTextFromPDFPage(string pdfFile, int pageNumber){PdfReader reader = new PdfReader(pdfFile);string text = PdfTextExtractor.GetTextFromPage(reader, pageNumber);try { reader.Close(); }catch { }richTextBox1.Text = text;}} }
========
C#如何給PDF文件添加水印
這篇文章主要為大家詳細介紹了C#如何給PDF文件添加水印的相關資料,具有一定的參考價值,
水印種類及功能介紹?
? ? PDF水印分為兩種:文本水印和圖片水印。文本水印一般被用在商業領域,提醒讀者該文檔是受版權保護的,其他人不能抄襲或者免費使用。除了這個特征,水印還可以用來標記這個文檔
的一些基本狀態信息,例如是草稿狀態還是最終版本?圖片水印是美化PDF文件的一個很好的選擇,它可以用多彩的、獨特的圖片來作為PDF文件的背景。那么,怎樣用編程的方式給PDF文件
添加水印呢?有很多種實現方法,其中一種最快最容易的辦法也許是用第三方軟件,例如Spire.PDF。本文會闡述怎樣用免費的第三方軟件Spire.PDF來給PDF文件添加文本水印和圖片水印。?
免費版Spire.PDF軟件介紹?
? ? 免費版Spire.PDF軟件是一款免費的獨立的PDF控件,它提供給編程者一系列豐富的PDF功能,例如讀,寫,新建,編輯,操作和通過C#或VB.NET轉化PDF文件等。請注意,免費版僅支
持10頁的PDF文件和三頁的轉換功能。?
? ? 首先,請從E-iceblue website網站上下載并安裝Spire.PDF。安裝完成后,你就可以利用“SampleCenter”和界面幫助快速開始了,其中有很多代碼片段和詳細的應用程序功能介紹。
下面就列舉一些怎樣給PDF文件添加圖片水印和文本水印的代碼片段。我把它分為兩部分。一部分是圖片水印,另一部分是文本水印。?
第一部分:添加圖片水印?
? ? 首先,準備一張你想設置為PDF文件水印的圖片。其次,我們只需要調用Image.FromFile(stringfilename)方法來加載圖片,非常簡單、方便。然后,設置PDF圖片背景。
代碼如下:
步驟1:創建一個新的PDF實例。然后導入PDF文件
?
PdfDocument pdf = new PdfDocument();?
pdf.LoadFromFile("sample.pdf");
步驟2:獲取PDF文件的第一頁
PdfPageBase page = pdf.Pages[0];
步驟3:導入圖片并把它設置為PDF文件的背景
Image img = Image.FromFile("img.jpg");?
page.BackgroundImage = img;?
?
步驟4:保存文件為PDF格式,命名為"ImageWaterMark.pdf"
pdf.SaveToFile("ImageWaterMark.pdf");?
添加了圖片水印的效果圖如下:
圖片 1: 圖片水印?
第二部分:添加文本水印?
? ? 和添加圖片水印不同的是,添加文本水印更為復雜。為了最好的匹配PDF頁面,我們需要在PDF中制作出水印文本,然后設置文本的字體,顏色,位置和文本格式。以上兩種功能均可以通
過調用這種方法來快速實現:DrawString(strings, PdfFontBase font, PdfBrush brush, float x, float y, PdfStringFormat format).下面是代碼片段:?
步驟1:創建一個新的PDF實例。然后導入PDF文件。
?
PdfDocument pdf= new PdfDocument();
pdf.LoadFromFile("sample.pdf");?
?
步驟2:獲取PDF文件的第一頁
PdfPageBase page = pdf.Pages[0];?
步驟3:添加文本水印到文件的第一頁,設置文本格式
PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));?
brush.Graphics.SetTransparency(0.3f);?
brush.Graphics.Save();?
brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);?
brush.Graphics.RotateTransform(-45);?
brush.Graphics.DrawString("Draft Version", new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Blue,0, 0, new PdfStringFormat(PdfTextAlignment.Center));?
brush.Graphics.Restore();?
brush.Graphics.SetTransparency(1);?
page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
?
步驟4:保存文件為PDF格式,命名為"TextWaterMark.pdf"
pdf.SaveToFile("TextWaterMark.pdf");?
?添加了文本水印的效果圖如下:
圖片 2: 文本水印?
總結
? ? 雖然有很多文章介紹了不用第三方軟件就可以用編程的方式來添加水印的方法,但這里我仍然使用了免費版的Spire.PDF軟件,因為除了水印功能以外,我還需要使用新建,轉換,打印和
保護PDF等功能,而這個軟件全部支持這些功能。它工作的很好,并且大大的提高了我的工作效率。如果你也感興趣的話,不妨試試它。
========
總結
- 上一篇: 图解使用CURL下载和上传文件
- 下一篇: dnet 并行编程学习总结