C# PDF附件生成

最近项目上需要生成行业某证件,查阅了一下,大体有两个思路可以实现

1.图片格式

2.PDF格式

使用图片格式,GDI+绘图的形式,GDI+绘图相关库资料比较多,难度也还好,问题是生成的证不是很好看,看上去别扭。最后还是决定用PDF格式生成

查阅了PDF生成相关资料,C#的相当相当少。已有的库,查阅到了包括 Aspose.PDF,QuestPDF,IText7

Aspose.PDF是商业版,需要授权,资料很少,尝试着写了一点,不是很好实现。

QuestPDF,查了以下资料,让人眼前一亮的写法,全部靠lambda表达式的方式操作,使用起来较容易上手

本地写完之后,放到IIS中,发现与IIS冲突,未查到解决资料。大体报的异常:

Unable to load library 'libSkiaSharp'

QuestPDF.Drawing.FontManager”的类型初始值设定项引发异常

只能放弃

因此,今天主要介绍iText7库的使用。

一、iText7 生成PDF

1.iText7 字体处理

默认的字体,除了显示不好看以外,还容易不显示中文。一直觉得字体是最简单,最常用的部分,应该类似 .setFont("宋体")的形式就可以实现,而pdf相关操作库中,字体处理都稍微麻烦。

FontProgram fontProgram =FontProgramFactory.CreateFont(fontpath);
PdfFont fontTitle = PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H);

fontTitle对象可以在后续的代码中直接使用。

说明:上面主要参数是 字体库的路径。此处需要注意,对于windows默认的字体,可以直接通过路径 “C:/windows/Fonts/simhei.ttf” 引用,对于非操作系统自带的字体,用户自己安装的字体,不能从 “C:/windows/Fonts"路径找到安装后的路径加载,通过windows路径加载,会产生如下错误:

System.IO.IOException:“C:\Windows\Fonts\方正大标宋简体.ttf not found as file or resource.

 需要使用下载的原字体文件(比如:“D:\TEMP\fonts\SourceHanSansCN-Medium-2.otf”)进行直接加载。

另外,windows/fonts中,除了包含 .ttf的字体,还包括 .ttc的字体,该类字体大体是一种集合的形式,具体加载代码如下:

PdfFont titleFont = PdfFontFactory.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0",PdfEncodings.IDENTITY_H);

以上路径字符,第一个是字体路径,第二个数值,代表的应该是字体在集合中的索引。

另外,关于字体版权,有些字体是需要授权的,不授权的话无法再pdf库中使用,会报如下错误

iText.Kernel.Exceptions.PdfException:“FZDBSJW--GB1-0Regular cannot be embedded due to licensing 

2.页面设置

PdfWriter writer = new PdfWriter(@"D:\TEMP\nn.pdf");
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
pdf.SetDefaultPageSize(PageSize.A4.Rotate());

3.背景图片设置

//背景图片
PdfCanvas canvas = new PdfCanvas(pdf.AddNewPage());
canvas.AddImageFittedIntoRectangle(ImageDataFactory.Create(backgroundimg), PageSize.A4.Rotate(), false);

4.表格相关

Table table = new Table(UnitValue.CreatePercentArray(new float[] { 3,5,4f,5})).UseAllAvailableWidth();
table.SetMarginLeft(120);
table.SetMarginRight(100);
table.SetMarginTop(16);

第一行数组指代表格的列数,每列宽度所占比。Cell的SetWidth()方法测试无效(可能是我用法不对)

上述setMarginLeft之类的方法,与html中 margin类似

5.一个Paragraph中多个样式

Paragraph py = new Paragraph("2023").SetFont(fontTNR).SetFontSize(valFontSize);
Paragraph pyc = new Paragraph("年").SetFont(fontDX).SetFontSize(valFontSize);
Paragraph pm = new Paragraph("05").SetFont(fontTNR).SetFontSize(valFontSize);
Paragraph pmc = new Paragraph("月").SetFont(fontDX).SetFontSize(valFontSize);
Paragraph groupPP = new Paragraph();
groupPP.Add(py).Add(pyc).Add(pm).Add(pmc);

6.图片插入

var ii = QRAssister.GetQRCode("http://www.baidu.com", 100, 100);
            Image img = new Image(ImageDataFactory.Create(ii, System.Drawing.Color.Transparent));
            img.SetWidth(70);
            img.SetHeight(70);
            img.SetMarginTop(-85);
            img.SetMarginLeft(190);
            document.Add(img);

二、QuestPDF库生成PDF

0.开始

QuestPDF库通过lambda表达式的方式使用,代码看上去比较神奇。

Document.Create(container =>
            {
                container.Page(page =>
                {
                    //设置页面
                    page.Size(PageSizes.A4.Landscape());
                    
                    
                    //设置内容
                    page.Content()
                        .PaddingVertical(2, Unit.Centimetre)
                        .Column(x =>
                        {
                            x.Spacing(20);
                                                
 x.Item().AlignCenter().Text("此处写入文字内容").FontSize(30).LetterSpacing(0.3f).Bold();

                            
                                });
                            });
                        });
                });
            })
            .GeneratePdf(pdfpath);

1.字体处理

FontManager.RegisterFont(File.OpenRead(@"C:\Windows\Fonts\simhei.ttf")); //黑体
FontManager.RegisterFont(File.OpenRead(@"C:\Windows\Fonts\simsun.ttc")); //宋体
FontManager.RegisterFont(File.OpenRead(@"C:\Windows\Fonts\simfang.ttf")); //仿宋

2.页面设置

page.Size(PageSizes.A4.Landscape());
page.MarginTop(1, Unit.Centimetre);
page.MarginBottom(1, Unit.Centimetre);
page.MarginLeft(3, Unit.Centimetre);
page.MarginRight(3, Unit.Centimetre);
page.DefaultTextStyle(x => x.FontSize(20).FontFamily("黑体"));

3.背景图片

page.Background().Image(backgroundimg,ImageScaling.Resize);

4.图片插入

 x.Item().Row(r => {
    var ii = r.ConstantItem(7, Unit.Centimetre).AlignLeft().PaddingLeft(10);
    ii.Image(qrpath, ImageScaling.FitHeight);
});

问题:class path resource [static/font/SIMLI.TTF cannot be resolved to URL because it does not exist. 这个错误是因为找不到指定路径下的文件而致的。根据引用中提到的方法,你可以使用grep命令在Linux中查找文件内容中含有某字符串的文件。但是这并不适用于你的问题。 对于你的问题,你需要检查路径中的文件是否存在。在这种情况下,你需要确保static/font文件夹下的SIMLI.TTF文件存在。如果文件确实存在,那么可能是路径配置不正确导致无法找到文件。你可以检查你的配置文件或代码中指定的路径是否与实际文件路径匹配。 如果文件确实不存在,那么你需要确保你正确地将文件放置在指定的路径下。你可以尝试重新复制文件到正确的位置。 总之,你需要检查文件路径的正确性,并确保对应的文件存在于指定路径下。如果问题仍然存在,你可能需要进一步检查你的配置或代码中的错误。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [一些linux和OpenGL的笔记](https://blog.youkuaiyun.com/weixin_33742618/article/details/93835625)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值