介绍语 本号主要是Java常用关键技术点,通用工具类的分享;以及springbootspringcloudMybatisplusdruidmysqlredisswaggermavendocker等集成框架的技术分享;datax、kafka、flink等大数据处理框架的技术分享。文章会不断更新,欢迎码友关注点赞收藏转发! 望各位码友点击关注,冲1000粉。后面会录制一些视频教程,图文和视频结合,比如:图书介绍网站系统、抢购系统、大数据中台系统等。技术才是程序猿的最爱,码友们冲啊 如果码友觉得代码太长,可以从头到尾快速扫射一遍,了解大概即可。觉得有用后再转发收藏,以备不时之需。 正文: pdf工具类,前面excel导出的时候一个码友问有没有pdf的工具类,我翻看了一下项目,没找到。以前有一个项目是有pdf导出的,主要是导出一些发函有公章的文件,还有需求是导出报销发票有公章等的文件,都是定制化的,耦合太大了,有些项目是要求导出网页的内容,这个是前端直接导出pdf,根本不需要后端支持。所以我自己整理写了一个工具类,抛砖引玉,有需求的码友可以自己根据公司需求定制pdf的生成工具类。这里只是给出一个非常基本的工具类,仅提供导出,仅供参考。欢迎多沟通使用例子importorg。junit。Test;importjava。util。ArrayList;importjava。util。List;publicclassPdfUtilTest{TestpublicvoidcreateTest(){ListPdfChapterpdfChaptersnewArrayList();pdfChapters。add(createContent());pdfChapters。add(createContent());pdfChapters。add(createContent());PdfUtil。getInstance()。init()。create(test14。pdf)。chapters(pdfChapters)。build();}privatePdfChaptercreateContent(){PdfChapterpdfChapternewPdfChapter();pdfChapter。setTitle(Pdf工具类);pdfChapter。setOrder(1);PdfSectionsectionnewPdfSection();section。setTitle(工具类例子1);PdfTextpdfTextnewPdfText();pdfText。setText(工具类内容内容);pdfText。setImage(true);pdfText。setImagePath(C:UsersliangxnDesktop20211106002429。png);section。getPdfTexts()。add(pdfText);pdfChapter。getSections()。add(section);returnpdfChapter;}} 上面例子导出的pdf如下,有几页,每页的内容是一样的,含有一张图片。这里提一下,图片和内容的布局,不是那么简单的,需要根据需求定制代码。 工具类源码:importcom。itextpdf。text。;importcom。itextpdf。text。pdf。BaseFont;importcom。itextpdf。text。pdf。PdfWriter;importorg。slf4j。Logger;importorg。slf4j。LoggerFactory;importjava。io。File;importjava。io。FileNotFoundException;importjava。io。FileOutputStream;importjava。io。IOException;importjava。net。URL;importjava。util。List;pdf工具类,主要是实现了导出功能。使用itextpdf包实现publicclassPdfUtil{privatestaticfinalLoggerloggerLoggerFactory。getLogger(PdfUtil。class);pdf大小,设置为A4纸大小publicstaticfinalRectanglePAGESIZEPageSize。A4;设置内容距离纸张上右下左的距离publicstaticfinalfloatMARGINLEFT50;publicstaticfinalfloatMARGINRIGHT50;publicstaticfinalfloatMARGINTOP50;publicstaticfinalfloatMARGINBOTTOM50;空格的间距大小publicstaticfinalfloatSPACING20;标题对齐方式:0表示left,1表示centerpublicstaticfinalintTITLEALIGNMENT1;privatestaticvolatilePdfUtilinstancenull;pdf文档privateDocumentdocumentnull;文章标题字体privateFontchapterFontnull;小节标题字体privateFontsectionFontnull;内容字体privateFonttextFontnull;privatePdfUtil(){}DCL(DoubleCheckLock双端捡锁机制)publicstaticPdfUtilgetInstance(){if(instancenull){synchronized(PdfUtil。class){if(instancenull){instancenewPdfUtil();}}}returninstance;}初始化字体protectedPdfUtilinit(){默认设置chapterFontcreateFont(20,Font。BOLD,newBaseColor(0,0,255));sectionFontcreateFont(16,Font。BOLD,newBaseColor(0,0,255));textFontcreateFont(10,Font。NORMAL,newBaseColor(0,0,0));returninstance;}初始化字体protectedPdfUtilinit(FontchapterFont,FontsectionFont,FonttextFont){使用自定义的字体chapterFontchapterFont;sectionFontsectionFont;textFonttextFont;returninstance;}创建pdf文件paramfileName文件(全路径文件名)protectedPdfUtilcreate(StringfileName){FilefilenewFile(fileName);documentnewDocument(PAGESIZE,MARGINLEFT,MARGINRIGHT,MARGINTOP,MARGINBOTTOM);FileOutputStreamoutnull;try{outnewFileOutputStream(file);PdfWriter。getInstance(document,out);}catch(FileNotFoundExceptione){logger。error(创建pdf文件异常,e);}catch(DocumentExceptione){logger。error(创建pdf文件错误,e);}打开文档准备写入内容document。open();returninstance;}protectedPdfUtilchapters(ListPdfChapterpdfChapters){try{for(PdfChapterpdfChapter:pdfChapters){ChapterchapterwriteChapter(pdfChapter);for(PdfSectionpdfSection:pdfChapter。getSections()){SectionsectionwriteSection(chapter,pdfSection);for(PdfTextpdfText:pdfSection。getPdfTexts()){if(pdfText。isImage()){writeImage(pdfText。getImagePath());}if(pdfText。getText()!null){section。add(writePhrase(pdfText。getText()));}}}document。add(chapter);}}catch(DocumentExceptione){e。printStackTrace();}returninstance;}protectedvoidbuild(){closeDocument();}写章节parampdfChapterprivateChapterwriteChapter(PdfChapterpdfChapter){ParagraphchapterTitlenewParagraph(pdfChapter。getTitle(),chapterFont);chapterTitle。setAlignment(TITLEALIGNMENT);ChapterchapternewChapter(chapterTitle,pdfChapter。getOrder());chapter。setNumberDepth(pdfChapter。getDepth());returnchapter;}写片段paramchapterparampdfSectionreturnprivateSectionwriteSection(Chapterchapter,PdfSectionpdfSection){Sectionsectionnull;if(chapter!null){ParagraphsectionTitlenewParagraph(pdfSection。getTitle(),sectionFont);sectionTitle。setSpacingBefore(SPACING);sectionchapter。addSection(sectionTitle);section。setNumberDepth(pdfSection。getDepth());}returnsection;}写内容paramtextprivatePhrasewritePhrase(Stringtext){returnnewParagraph(text,textFont);}写图片paramimageprivatevoidwriteImage(Stringimage){try{图片1Imageimage1Image。getInstance(image);将图片1添加到pdf文件中document。add(image1);}catch(IOExceptione){logger。error(写入图片异常,e);}catch(DocumentExceptione){logger。error(写入图片错误,e);}}功能:返回支持中文的字体仿宋psimfang。ttf仿宋常规psimhei。ttf黑体常规paramsize字体大小paramstyle字体风格paramcolor字体颜色return字体格式privateFontcreateFont(floatsize,intstyle,BaseColorcolor){BaseFontbaseFontnull;try{simfang。ttf文件必须放在class类文件所有的包路径下URLresourcePdfUtil。class。getClassLoader()。getResource(simfang。ttf);if(resourcenull){thrownewMyAppRunException(无simfang。ttf字体文件);}logger。info(加载simfang。ttf字体,路径:{},resource。getPath());baseFontBaseFont。createFont(resource。getPath(),BaseFont。IDENTITYH,BaseFont。EMBEDDED);}catch(DocumentExceptione){logger。error(加载字体错误,e);}catch(IOExceptione){logger。error(加载字体错误,e);}returnnewFont(baseFont,size,style,color);}最后关闭PDF文档privatevoidcloseDocument(){if(document!null){执行关闭时文件会自动保存document。close();logger。info(文件已保存);}}} 其他类:通用异常类publicclassMyAppRunExceptionextendsRuntimeException{publicMyAppRunException(Stringmessage){super(message);}publicMyAppRunException(Stringmessage,Throwablecause){super(message,cause);}publicMyAppRunException(Throwablecause){super(cause);}protectedMyAppRunException(Stringmessage,Throwablecause,booleanenableSuppression,booleanwritableStackTrace){super(message,cause,enableSuppression,writableStackTrace);}} maven依赖dependencygroupIdcom。itextpdfgroupIditextpdfartifactIdversion5。5。13。2versiondependency 外话,pdf的需求基本都是需要定制的,不是一个工具类能搞定的。这里给出处理pdf的另一个包,这个包是apache的包,对于读pdf非常好用。需要定制pdf导出的话,还是需要多了解这两个包,然后定制自己的工具类。dependencygroupIdorg。apache。pdfboxgroupIdpdfboxartifactIdversion2。0。24versiontypebundletype!要使用bundle需要先依赖一个plugin,自行百度dependency 鄙人编码十年多,在项目中也积累了一些工具类,很多工具类在每个项目都有在用,很实用。大部分是鄙人封装的,有些工具类是同事封装的,有些工具类已经不记得是ctrlc的还是自己封装的了,现在有空就会总结项目中大部分的工具类,分享给各位码友。如果文章中涉及的代码有侵权行为请通知鄙人处理。 计划是先把工具类整理出来,正所谓工欲善其事,必先利其器。项目中不管是普通单体项目还是多模块maven项目或是分布式微服务,一部分功能模块都是可以重用的,工具类模块就是其中之一。