C#操作PDF总结

本文详细介绍使用C#生成PDF的方法,包括基本文档创建、页面设置、多页文档生成、插入图片、读取PDF内容及使用iTextSharp进行水印添加等。通过实际代码示例,帮助读者快速掌握C# PDF操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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等功能,而这个软件全部支持这些功能。它工作的很好,并且大大的提高了我的工作效率。如果你也感兴趣的话,不妨试试它。
========
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值