码迷,mamicode.com
首页 > 其他好文 > 详细

iTextSharp 读出,写入

时间:2014-06-25 15:13:27      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

版本为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();
    }    
}

 

下载

iTextSharp 读出,写入,布布扣,bubuko.com

iTextSharp 读出,写入

标签:style   class   blog   code   http   tar   

原文地址:http://www.cnblogs.com/hongdada/p/3806576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!