C#生成PDF总结

(一)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#转为属性,可以作为参考文档。

 

 

posted @ 2013-02-26 17:37  焦涛  阅读(73819)  评论(10编辑  收藏  举报