java 导出pdf 证书

近期在做导出pdf,但是在网上找的都是导出pdf表格或者就是根据模板导出,但是我要的是导出证书,所以我就在想了一下然后参考了一下链接,直接把照片当成水印在最后面,然后把相应的数据填写在相应的位置里面,效果如下:
在这里插入图片描述
1.这个是生成中文内容中字体的样式封装类

package com.springboot.wensocket.importexport.entity;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;

public class ContentStyle {

    private String TTFPath = "F:\\IdeaProject\\wensocket\\src\\main\\resources\\simhei.ttf";// 字体类型
    private float  fontSize = 12;//字体大小
    private BaseColor baseColor = new BaseColor(0, 0, 0);//默认是黑色
    private int style = Font.NORMAL;//字体样式
    private int alignment = Element.ALIGN_LEFT;

    public String getTTFPath() {
        return TTFPath;
    }
    public void setTTFPath(String tTFPath) {
        TTFPath = tTFPath;
    }
    public float getFontSize() {
        return fontSize;
    }
    public void setFontSize(float fontSize) {
        this.fontSize = fontSize;
    }
    public BaseColor getBaseColor() {
        return baseColor;
    }
    public void setBaseColor(BaseColor baseColor) {
        this.baseColor = baseColor;
    }
    public int getStyle() {
        return style;
    }
    public void setStyle(int style) {
        this.style = style;
    }
    public int getAlignment() {
        return alignment;
    }
    public void setAlignment(int alignment) {
        this.alignment = alignment;
    }
}

2.导出pdf工具类

package com.springboot.wensocket.importexport.entity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFUtil {

    private Document document;
    private PdfWriter writer;

    public void setDocument(Document document) {
        this.document = document;
    }

    public void setWriter(PdfWriter writer) {
        this.writer = writer;
    }
    /**
     * 开启创建PDF对象
     * @param pafPath : 生成pdf的磁盘路径
     * @return
     * @throws FileNotFoundException
     * @throws DocumentException
     */
    public PDFUtil openDocumnet(String pafPath) throws FileNotFoundException, DocumentException{
        Document document = new Document(PageSize.A4);
        writer = PdfWriter.getInstance(document,new FileOutputStream(pafPath));
        document.open();
        this.document = document;
        return this;
    }
    /**
     * 添加图片背景
     * @param imageUrl :证书图片的磁盘路径
     * @param absoluteX :左边距
     * @param absoluteY :底边距
     * @return
     * @throws MalformedURLException
     * @throws IOException
     * @throws DocumentException
     */
    public PDFUtil addImage(String imagePath,float absoluteX, float absoluteY) throws MalformedURLException, IOException, DocumentException{
        Image tImgCover = Image.getInstance(imagePath);
        tImgCover.setAbsolutePosition(absoluteX, absoluteY);
        float heigth = tImgCover.getHeight();
        float width = tImgCover.getWidth();
        // int percent=getPercent(heigth, width);
        int percent = getPercent2(heigth, width);
        // 设置图片居中显示
        // tImgCover.setAlignment(Image.MIDDLE);
        tImgCover.scalePercent(percent);// 表示是原来图像的比例;
        document.add(tImgCover);
        return this;
    }
    /**
     *
     * @param certificateContent :pdf证书的中文内容
     * @param x :左边距
     * @param y :底边距
     * @param contentStyle :中文内容的样式
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public PDFUtil addContent(String certificateContent,float x, float y,ContentStyle contentStyle) throws DocumentException, IOException{

        if(contentStyle == null){
            contentStyle = new ContentStyle();
        }

        PdfContentByte canvas = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(contentStyle.getTTFPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font secFont = new Font(bf, contentStyle.getFontSize(), contentStyle.getStyle(), contentStyle.getBaseColor());
        Phrase certificateContentPhrase = new Phrase(certificateContent, secFont);
        ColumnText.showTextAligned(canvas, contentStyle.getAlignment(), certificateContentPhrase, x,y, 0);
        return this;
    }
    /**
     * 添加日期内容
     * @param x 插入pdf左边距
     * @param y 插入pdf底边距
     * @param contentStyle
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public PDFUtil addDateContent(float x, float y,ContentStyle contentStyle) throws DocumentException, IOException{

        if(contentStyle == null){
            contentStyle = new ContentStyle();
        }

        Date currentDate = PDFUtil.getCurrentDate();
        String currentDateString = PDFUtil.DateToString(currentDate);

        PdfContentByte canvas = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(contentStyle.getTTFPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font secFont = new Font(bf, contentStyle.getFontSize(), contentStyle.getStyle(), contentStyle.getBaseColor());
        Phrase certificateDatephrase = new Phrase(currentDateString, secFont);
        ColumnText.showTextAligned(canvas,contentStyle.getAlignment(), certificateDatephrase, x,y, 0);
        return this;
    }
    /**
     * 释放资源
     */
    public void close(){
        document.close();
    }
    /**
     * 第二种解决方案,统一按照宽度压缩
     * 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
     * @param args
     */
    public int getPercent2(float h,float w)
    {
        int p=0;
        float p2=0.0f;
        p2=595/w*100;
        System.out.println("--"+p2);
        p=Math.round(p2);
        return p;
    }
    /**
     * 第一种解决方案
     * 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
     * @param h
     * @param w
     * @return
     */

    public int getPercent(float h,float w)
    {
        int p=0;
        float p2=0.0f;
        if(h>w)
        {
            p2=297/h*100;
        }
        else
        {
            p2=210/w*100;
        }
        p=Math.round(p2);
        return p;
    }

    /**
     *  日期
     * @return
     */
    public static java.util.Date getCurrentDate(){
        return new java.util.Date(System.currentTimeMillis());
    }
    public static String DateToString(Date date) {
        if(date == null){
            return "";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 测试
     * @param args
     * @throws MalformedURLException
     * @throws FileNotFoundException
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws MalformedURLException, FileNotFoundException, DocumentException, IOException {
        long currentDateTime = new Date().getTime();
        //背景照片的路径
        String imagePath = PDFUtil.class.getClassLoader().getResource("static/img/9.png").getPath();
        //生成的路径
        String pdfFilePath = "f:/" +getCurrentDate()+ ".pdf";
        PDFUtil pdfUtil = new PDFUtil();
        pdfUtil.openDocumnet(pdfFilePath)
                .addImage(imagePath, 0, 400)
                .addDateContent(340,440,null)
                .addContent("inco",83,635,null)
                .close();
    }
}

3.pom.xml

<dependency>
	    <groupId>com.itextpdf</groupId>
	    <artifactId>itextpdf</artifactId>
	    <version>5.5.11</version>
	   </dependency>
	   
	   <dependency>
		    <groupId>com.itextpdf</groupId>
		    <artifactId>itext-asian</artifactId>
		    <version>5.2.0</version>
		</dependency>

备:如果没有字体类型的话,在这里下载“字体类型”(提取码:2p2k)
我这个是参考的“路径

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java导出PDF文件,你可以使用一些开源库和框架来实现。以下是一种常见的方法: 1. 首先,你需要添加相关的依赖项到你的项目中。一个常用的Java库是 Apache PDFBox,它提供了创建和操作PDF文件的功能。你可以在你的构建工具中添加以下依赖项: ```xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.26</version> </dependency> ``` 2. 创建一个PDF文档对象,并添加内容到文档中。下面是一个简单的示例代码: ```java import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.PDPageContentStream; import java.io.File; import java.io.IOException; public class PDFExporter { public static void main(String[] args) { try { // 创建一个新的PDF文档 PDDocument document = new PDDocument(); // 添加一个页面 PDPage page = new PDPage(PDRectangle.A4); document.addPage(page); // 创建页面内容流 PDPageContentStream contentStream = new PDPageContentStream(document, page); // 添加文本到页面 contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.newLineAtOffset(100, 700); contentStream.showText("Hello, World!"); contentStream.endText(); // 关闭流并保存文档 contentStream.close(); document.save(new File("output.pdf")); // 关闭文档 document.close(); System.out.println("PDF导出完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码将创建一个包含 "Hello, World!" 文本的PDF文件。你可以根据自己的需求修改代码来添加更多内容和样式。 3. 运行代码,你将在项目的根目录下找到名为 "output.pdf" 的PDF文件,它就是导出PDF文档。 这只是一个简单的示例,你可以根据实际需求进行更复杂的PDF操作。希望能帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值