2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > itextpdf通过pdf模板生成pdf文件

itextpdf通过pdf模板生成pdf文件

时间:2019-12-03 04:46:21

相关推荐

itextpdf通过pdf模板生成pdf文件

itextpdf通过pdf模板生成pdf文件,设置粗体字体

1.创建pdf模板2.使用模板生成pdf3.itext自带的字体列表4.遇到的坑

1.创建pdf模板

可以使用PDFFescape网站来线上创建pdf模板,网页链接:/windows/ 或者 /open/

本地建好一个pdf模板,需要填充数据的地方空着,生成一个pdf文件,然后点击我下图框起来的地方上传pdf文件。

点击下图框起来对的地方,然后创建表单域,在需要填充文字的地方用鼠标拉一下就行了。

就会出现这种样子的表单域

可以右键编辑一下表单域的属性

name是表单域的名称,这个可以编辑,而且要记下来,后面使用itextpdf填充表单域的时候需要用的这个。

编辑完成之后,可以点击左边的下载按钮,将编辑后的pdf文件下载下来。这样模板就完成了

2.使用模板生成pdf

导入依赖

<!-- itext --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.2</version></dependency><!--pdf itext 的jar依赖 --><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>

创建pdf文件代码

@AutowiredResourceLoader resourceLoader;/*** 生成pdf* @param vo* @param templateName*/public void createDisplayCardPdf(Vo vo, String templateName) {try {// pdf模板所在路径,就是网站制作好后下载的pdf模板路径Resource resource = resourceLoader.getResource("classpath:template/" + templateName);PdfReader reader = new PdfReader(resource.getInputStream());ByteArrayOutputStream bos = new ByteArrayOutputStream();PdfStamper ps = new PdfStamper(reader, bos);AcroFields fields = ps.getAcroFields();//填充文本fillData(fields, vo);ps.setFormFlattening(false);//生成文件名String filename = "qrcode";//生成二维码图片文件File bufferedImage = QRCodeUtils.createQrCodeFile(vo.getUrl(), path, filename, 400, 400);try {//PDF附件加上二维码水印PdfUtils.setWatermarkForPDF(ps, bufferedImage, 654, 83, 135, 135);} catch (Exception e) {throw new RuntimeException("pdf文件生成失败");} finally {//删除文件if (bufferedImage != null) {bufferedImage.delete();}}ps.close();//生成pdf路径存放的路径OutputStream fos = new FileOutputStream("D:/111/result.pdf");fos.write(bos.toByteArray());fos.flush();fos.close();bos.close();} catch (Exception e) {throw new RuntimeException(e.getMessage());}}/*** 填充模板中的数据*/public void fillData(AcroFields fields, Vo vo) {try {// 为字段赋值,注意字段名称是区分大小写的//设置字体大小float bigFontSize = 22;float textFontSize = 17;//中文字体 微软雅黑加粗//注意:BaseFont无法加粗,想要使用粗体的话需要使用粗体的字体BaseFont fontBold = BaseFont.createFont("D:\\111\\wryhBold.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//这样用于解决使用自定义字体导致pdf文件大小变大fontBold.setSubset(true);//嵌入只使用的字体//carBrandAndModel是之前设置的表单域的name//设置这个表单域的字体 fields.setFieldProperty("carBrandAndModel", "textfont", fontBold , null);//设置这个表单域的字体大小fields.setFieldProperty("carBrandAndModel", "textsize", bigFontSize, null);//设置这个表单域的字体颜色BaseColor baseColor = BaseColor.WHITE;fields.setFieldProperty("carBrandAndModel", "textcolor", baseColor, null);//给表单域填充文本(一定要放在最后,不然设置的样式不生效)fields.setField("carBrandAndModel", vo.getCarBrandAndModel());} catch (Exception e) {throw new RuntimeException(e.getMessage());}}

package mon.utils;import com.itextpdf.text.BadElementException;import com.itextpdf.text.BaseColor;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Image;import com.itextpdf.text.pdf.PdfContentByte;import com.itextpdf.text.pdf.PdfGState;import com.itextpdf.text.pdf.PdfStamper;import java.io.File;import java.io.IOException;public class PdfUtils {/*** 为PDF附件添加图片* @param stamper pdf文件* @param imageFile 图片* @param x 坐标* @param y* @throws IOException* @throws DocumentException*/public static void setWatermarkForPDF(PdfStamper stamper, File imageFile,int x,int y,int width,int height)throws IOException, DocumentException {PdfContentByte waterMar;PdfGState gs = new PdfGState();long startTime = System.currentTimeMillis();waterMar = stamper.getOverContent(1);// 在内容上方加水印// waterMar = stamper.getUnderContent(1);//在内容下方加水印// 设置图片透明度为0.2fgs.setFillOpacity(1f);// 设置笔触字体不透明度为0.4f//gs.setStrokeOpacity(0.4f);// 开始水印处理waterMar.beginText();// 设置透明度waterMar.setGState(gs);// 设置水印字体参数及大小//waterMar.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 60);// 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度//waterMar.showTextAligned(Element.ALIGN_CENTER, "公司内部文件,请注意保密!", 500, 430, 45);// 设置水印颜色waterMar.setColorFill(BaseColor.GRAY);// 创建水印图片Image itextimage = getImage(imageFile);// 水印图片位置itextimage.setAbsolutePosition(x, y);// 边框固定itextimage.scaleToFit(200, 200);// 设置旋转弧度//image.setRotation(30);// 旋转 弧度// 设置旋转角度//image.setRotationDegrees(45);// 旋转 角度// 设置等比缩放//itextimage.scalePercent(90);// 自定义大小itextimage.scaleAbsolute(width, height);// 附件加上水印图片waterMar.addImage(itextimage);// 完成水印添加waterMar.endText();// strokewaterMar.stroke();}private static Image getImage(File image) throws IOException, BadElementException {return Image.getInstance(image.getPath());}}

/*** 生成二维码图片* @param url* @param path 文件路径* @param fileName 文件名 不用带后缀* @param width 图片宽度* @param height 图片高度* @return png图片* @throws IOException*/public static File createQrCodeFile(String url,String path,String fileName,int width ,int height) throws IOException{BitMatrix bitMatrix = createCode(url, width, height);bitMatrix = deleteWhite(bitMatrix);BufferedImage image = toBufferedImage(bitMatrix);File file = new File(path + fileName + ".jpg");String format = "jpg";if (!ImageIO.write(image, format, file)) {throw new IOException("Could not write an image of format " + format + " to " + file);}return file;}

3.itext自带的字体列表

使用方法

BaseFont fontBold1 = BaseFont.createFont("Helvetica-Bold", "", BaseFont.NOT_EMBEDDED);

4.遇到的坑

使用自定义字体无法加粗

解决:使用加粗的字体

使用加粗字体的时候,如果用下面的代码设置字体会导致中文才加粗,英文和数字不加粗

BaseFont fontBold = BaseFont.createFont(fontBoldPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);fields.addSubstitutionFont(fontBold);

使用下面的方法设置字体,英文中文都会加粗,但是生成的pdf文件很大,模板500kb,生成的pdf 9M

BaseFont fontBold = BaseFont.createFont(fontBoldPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);fields.setFieldProperty("carBrandAndModel", "textfont", fontBold, null);fields.setFieldProperty("carBrandAndModel", "textsize", bigFontSize, null);fields.setField("carBrandAndModel", vo.getCarBrandAndModel());

原因:fields.setFieldProperty这个方法设置字体时,会去查设置的BaseFont在原pdf中存不存在,不存在就直接把字体全集嵌入到pdf中,导致pdf文件变大。

解决: 只嵌入使用到的部分字体。

BaseFont fontBold = BaseFont.createFont(fontBoldPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);fontBold.setSubset(true);//嵌入只使用的字体fields.setFieldProperty("carBrandAndModel", "textfont", fontBold, null);fields.setFieldProperty("carBrandAndModel", "textsize", bigFontSize, null);fields.setField("carBrandAndModel", displayCardPdfVo.getCarBrandAndModel());

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。