天天看点

CSharp: itext7.* create pdf file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using iText.Kernel;
using iText.IO;
using iText.Html2pdf;
using com.itextpdf.layout;
using Common.Logging;
using Common.Logging.Factory;
using Org.BouncyCastle;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.X509;
using iText.Kernel.Font;
using iText.Kernel.Pdf.Filespec;
using iText.Kernel.Utils;
using iText.Kernel.XMP;
using iText.Kernel.XMP.Properties;
using iText.IO.Font.Constants;
using iText.Layout;
using System.IO;
using iText.Kernel.Pdf;		    //PdfWriter, PdfDocument
using iText.Kernel.Geom;	    //PageSize
using iText.Layout.Element;
using iText.Layout.Properties;
using iText.IO.Font;
using iText.IO.Image;
using iText.Kernel.Pdf.Action;
using iText.Kernel.Pdf.Annot;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Events;

namespace DuItexDemo
{


    /// <summary>
    /// geovindu Geovin Du
    /// 涂聚文
    /// iText7.1.11
    /// 
    /// </summary>
    public partial class _Default : System.Web.UI.Page
    {

        string path = "Styles/SIMLI.TTF";
        public PdfFont getPdfFont()
        {
            PdfFont pdfFont = null;
            try
            {
                pdfFont = PdfFontFactory.CreateFont(Server.MapPath(path), PdfEncodings.IDENTITY_H);

               // pdfFont = PdfFontFactory.CreateFont("STSong-Light", "UniGB-UCS2-H");
            }
            catch (Exception e)
            {
                e.Message.ToString();
            }
            return pdfFont;
        }
        /// <summary>
        /// geovindu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            byte[] USER_PASSWORD = Encoding.ASCII.GetBytes("geovindu"); //UTF8 ok
            byte[] OWNER_PASSWORD = Encoding.ASCII.GetBytes("geovindu");
            if (!IsPostBack)
            {
                PdfFont sysFont = PdfFontFactory.CreateRegisteredFont("C:/Windows/Fonts/simhei.ttf");

                String mytimes = DateTime.Now.ToString("yyyyMMdd_HH_mm_ss");
                string file = Server.MapPath("geovindu" + mytimes + ".pdf");
                

               // PdfWriter writer = new PdfWriter(file);
                WriterProperties w = new WriterProperties().SetStandardEncryption(USER_PASSWORD, OWNER_PASSWORD, EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
                PdfWriter writer = new PdfWriter(file,w);     

                PdfDocument pdf = new PdfDocument(writer);

                //string password = "geovindu@123";
                //PdfReader reader = new PdfReader(input);
                //PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);

                Document document = new Document(pdf, PageSize.A4.Rotate());


                //注册事件监听
                pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new DuEventHandler());


                document.SetFont(sysFont).SetFontSize(12);//设置字体大小
                //设置文档属性
                pdf.GetDocumentInfo().SetAuthor("涂聚文 C#");
                pdf.GetDocumentInfo().SetTitle("IText7 dotnet测试PDF CSharp ");
                pdf.GetDocumentInfo().SetSubject("涂聚文公司");
                pdf.GetDocumentInfo().SetMoreInfo("涂聚文", "111");
                pdf.GetDocumentInfo().SetCreator("geovindu CSharp");
                pdf.GetDocumentInfo().SetKeywords("IText涂聚文 Gevoin Du");

                //页边距
                document.SetMargins(20, 20, 20, 20);

                //简单文字
                document.Add(new Paragraph("简单文字").SetFont(getPdfFont()));
                document.Add(new Paragraph("Hello Word!").SetFont(getPdfFont()).Add(new Tab()).Add(new Text("你好!").AddStyle(new iText.Layout.Style().SetFontSize(24))));

                //简单图片
                document.Add(new Paragraph("简单图片").SetFont(getPdfFont()));

                document.Add(new iText.Layout.Element.Image(ImageDataFactory.Create(Server.MapPath("resource/geovindulogo.jpg"))));

                //简单表格
                document.Add(new Paragraph("简单表格").SetFont(getPdfFont()));
                iText.Layout.Element.Table table = new iText.Layout.Element.Table(new float[] { 3, 3, 4 });
                PdfFont font = getPdfFont();
                //标题、内容
                process(table, "姓名;年龄;电话号码", font, true);
                for (int i = 0; i < 5; i++)
                {
                    process(table, "涂聚文" + i + ";" + (18 + i) + ";1500000000" + i, font, false);
                }
                document.Add(table);

                //超链接
                document.Add(new Paragraph("超链接").SetFont(getPdfFont()));
                PdfLinkAnnotation annotation = new PdfLinkAnnotation(new Rectangle(0, 0));
                annotation.SetAction(PdfAction.CreateURI("https://itextpdf.com/"));
                Paragraph p = new Paragraph("更多精彩内容,猛戳:").SetFont(getPdfFont()).Add(new Link("这里", annotation));
                document.Add(p);

                pdf.AddNewPage();
                //换一页
                document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
                pdf.AddNewPage();
                document.Close();
                Response.Write("Ok!");
            }

        }
        /// <summary>
        /// geovindu
        /// </summary>
        /// <param name="table"></param>
        /// <param name="line"></param>
        /// <param name="font"></param>
        /// <param name="isHeader"></param>
        public void process(iText.Layout.Element.Table table, String line, PdfFont font, bool isHeader)
        {
            String[] split = line.Split(';');
            foreach (String s in split) {
            Cell cell = new Cell().Add(new Paragraph(s).SetFont(font));
                if (isHeader) 
                {
                    table.AddHeaderCell(cell);
                } 
                else
                {
                    table.AddCell(cell);
              }
           }
        }
        /// <summary>
        /// geoivndu
        /// </summary>
        /// <param name="pdfBase64"></param>
        /// <param name="passwordUser"></param>
        /// <param name="passwordOwner"></param>
        /// <returns></returns>
        public static string EncryptPDFwithPassword(string pdfBase64, string passwordUser, string passwordOwner)
        {
            var encryptedBase64 = string.Empty;
            var srcBytes = Convert.FromBase64String(pdfBase64);
            var userPassword = Encoding.ASCII.GetBytes(passwordUser);
            var ownerPassword = Encoding.ASCII.GetBytes(passwordOwner);

            PdfReader reader = new PdfReader(new MemoryStream(srcBytes));
            WriterProperties props = new WriterProperties()
                    .SetStandardEncryption(userPassword, ownerPassword, EncryptionConstants.ALLOW_PRINTING,
                            EncryptionConstants.ENCRYPTION_AES_128 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);

            using (var memoryStream = new MemoryStream())
            {
                PdfWriter writer = new PdfWriter(memoryStream, props);
                PdfDocument pdfDoc = new PdfDocument(reader, writer);
                pdfDoc.Close();
                encryptedBase64 = Convert.ToBase64String(memoryStream.ToArray());
            }

            return encryptedBase64;
        }

        /// <summary>
        /// geovindu
        /// </summary>
        /// <param name="outFile"></param>
        /// <param name="htmlDoc"></param>
        private void HTML2PDF(string outFile, string htmlDoc) {
            System.IO.FileInfo fi = new FileInfo( outFile );	
            PdfWriter writer = new PdfWriter( fi );
            
            //用法1 -- 使用默认参数直接转换(A4,)
            //HtmlConverter.ConvertToPdf(htmlDoc, writer);
             
            //用法2 -- 自定义页面大小、留白尺寸
            PdfDocument pdf = new PdfDocument( writer );
            PageSize a6 = PageSize.A6;
            a6.ApplyMargins(20, 20, 20, 20, false);		//if true the rectangle will expand, otherwise it will shrink
            pdf.SetDefaultPageSize( a6 );
            ConverterProperties prop= new ConverterProperties();	
            HtmlConverter.ConvertToPdf(htmlDoc, pdf, prop);
            
        }


    }
}
      

  

CSharp: itext7.* create pdf file
CSharp: itext7.* create pdf file
CSharp: itext7.* create pdf file

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)成功.---Geovin Du(涂聚文)