首页 > 代码库 > iTextSharp 读出,写入

iTextSharp 读出,写入

版本为5.1.2

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using System.Text;using iTextSharp;using iTextSharp.text;using iTextSharp.text.pdf;using iTextSharp.text.pdf.parser; public partial class _Default : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        string path = Server.MapPath("~/") + "Pdfs\\Doc1.pdf";        writePDF(path, "毛主席万岁!!!");        string content = readPDF(path);        Response.Write(content);    }    /// <summary>    /// 读出pdf文件(返回有换行符)    /// </summary>    /// <param name="fn">读出的pdf文件的路径和名称</param>    /// <returns></returns>    private string readPDF(string fn)    {        PdfReader reader = new PdfReader(fn);        StringBuilder strBuilder = new StringBuilder();        int num = reader.NumberOfPages;        for (var i = 1; i <= num; i++)        {            string text = PdfTextExtractor.GetTextFromPage(reader,num);            strBuilder.Append(text);        }        return strBuilder.ToString();    }    /// <summary>    /// 写入pdf文件    /// </summary>    /// <param name="fn">路径</param>    /// <param name="content">段落内容</param>    private void writePDF(string fn, string content)    {        //必须先加入资源        //string path = Server.MapPath("~/");        //BaseFont.AddToResourceSearch(path + "DLL\\iTextAsian.dll");        //BaseFont.AddToResourceSearch(path + "DLL\\iTextAsianCmaps.dll");        //"UniGB-UCS2-H" "UniGB-UCS2-V"是简体中文,分别表示横向字 和 纵向字        //"STSong-Light"是字体名称        //BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            ////可以使用 TTF 字体        //BaseFont bf0 = BaseFont.CreateFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);        BaseFont bf = BaseFont.CreateFont("c://windows//fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);        iTextSharp.text.Font font = new iTextSharp.text.Font(bf);        var doc1 = new Document();  //默认为A4大小        //var doc2 = new Document(PageSize.A5);        //var doc3 = new Document(new Rectangle(100f, 300f)); 宽100像素,高300像素         PdfWriter.GetInstance(doc1, new FileStream(fn, FileMode.Create));        doc1.Open();        doc1.Add(new Paragraph(content, font));        doc1.Close();    }    }

 

下载