CSharp: itext7.* create pdf file

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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);
             
        }
 
 
    }
}

  

 

 

 

posted @   ®Geovin Du Dream Park™  阅读(114)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示