itext简单实现点击页面预览PDF可下载

//拷贝即用
//pom文件引入依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

 @RequestMapping("/supervise_letter")
 public void pdf(HttpServletResponse response) {
     Map<String, Object> map = new HashMap<>();
     map.put("area", "锦江区");
     map.put("teLing", "TG1000001");
     map.put("num", "688");
     map.put("company", "成都xx有限公司");
     try {
         String title = "特种设备安全监察指令书";
         Document document = new Document();
         ServletOutputStream out = response.getOutputStream();
         ByteArrayOutputStream pdf = new ByteArrayOutputStream();
         PdfWriter.getInstance(document, pdf);
         //拼接字符串变量
         superviseLetterPDF(document, map);
         response.setContentType("application/pdf");
         response.setContentLength(pdf.size());
         response.setHeader("Content-Disposition", "inline;filename=" + new String(title.getBytes(), "ISO-8859-1") + ".pdf");
         pdf.writeTo(out);
         out.flush();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

 private static void superviseLetterPDF(Document document, Map<String, Object> map) throws DocumentException {
     document.open();
     //第一行标头
     Paragraph p1 = new Paragraph("特种设备安全监察指令书", PdfUtil.setFont(22f, BaseColor.BLACK, false));
     p1.setAlignment(Element.ALIGN_CENTER);
     document.add(p1);
     //第二行质监号
     Paragraph p2 = new Paragraph("(" + map.get("area") + ")质监特令[" + map.get("teLing") + "]第" + map.get("num") + "号", PdfUtil.setFont(12f, BaseColor.BLACK, false));
     p2.setAlignment(Element.ALIGN_CENTER);
     p2.setSpacingAfter(15f);
     p2.setSpacingBefore(15f);
     document.add(p2);
     //第二行质监号
     Paragraph p3 = new Paragraph(map.get("company").toString(), PdfUtil.setFont(12f, BaseColor.BLACK, false));
     p3.setAlignment(Element.ALIGN_LEFT);
     p3.setSpacingAfter(15f);
     p3.setSpacingBefore(15f);
     p3.add(new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2));
     document.add(p3);
     document.close();
 }

 

//下面是PDF工具类

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PDFUtil {
    private static Logger logger = LoggerFactory.getLogger(PDFUtil.class);

    /**
     * 设置字体
     *
     * @param fontSize
     * @param color
     * @param isBold
     * @return
     */
    public static Font setFont(Float fontSize, BaseColor color, Boolean isBold) {
        Font font = new Font();
        try {
            //中文字体,解决中文不能显示问题
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFont, fontSize, isBold ? Font.BOLD : Font.NORMAL, color);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("PDFUtil.setFont 设置字体出错  e={}", e);
        }
        return font;
    }

    /**
     * 设置Table
     *
     * @param numLine   列数
     * @param width     表格的宽度
     * @param upWidth   表格上面空白宽度
     * @param downWidth 表格下面空白宽度
     * @param floats    每列分别设置宽度
     * @return
     */
    public static PdfPTable setTable(int numLine, int width, float upWidth, float downWidth, float[] floats) {
        // 添加表格,3列
        PdfPTable table = new PdfPTable(numLine);
        // 设置表格宽度比例为%100
        table.setWidthPercentage(100);
        // 设置表格的宽度
        table.setTotalWidth(width);
        // 也可以每列分别设置宽度
        try {
            table.setTotalWidth(floats);
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error("PDFUtil.setTable 设置table出错  e={}", e);
        }
        // 锁住宽度
        table.setLockedWidth(true);
        // 设置表格上面空白宽度
        table.setSpacingBefore(upWidth);
        // 设置表格下面空白宽度
        table.setSpacingAfter(downWidth);
        // 设置表格默认为无边框
        table.getDefaultCell().setBorder(0);
        return table;
    }

    /**
     * 设置表格左右边距
     *
     * @param msg     表格内容
     * @param lineNum 表格占几列
     * @param lineNum 表格占几行
     * @param left
     * @param right
     * @param font
     * @return
     */
    public static PdfPCell setSpace(String msg, int lineNum, int rowNum, int left, int right, Font font) {
        // 字体样式
        PdfPCell cell = null;
        if (font == null) {
            cell = new PdfPCell(new Paragraph(msg));
        } else {
            cell = new PdfPCell(new Paragraph(msg, font));
        }
        // 设置行数
        cell.setColspan(lineNum);
        cell.setRowspan(rowNum);
        if (left > 0) {
            // 左边距
            cell.setPaddingLeft(left);
        }
        if (right > 0) {
            // 右边距
            cell.setPaddingRight(right);
        }
        return cell;
    }

    /**
     * 表格设置
     *
     * @param table
     * @param borderColor 边框颜色
     * @param center      居中
     * @param height      高度
     * @param border      无边框
     * @param cell
     * @return
     */
    public static void setCell(PdfPTable table, BaseColor borderColor, Boolean center, int height, Boolean border, PdfPCell cell) {
        // 左右居中
        if (center) {
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        }
        // 无边框
        if (border) {
            cell.setBorder(Rectangle.NO_BORDER);
        }
        // 边框颜色
        cell.setBorderColor(borderColor);
        // 上下居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        // 高度
        cell.setFixedHeight(height);
        table.addCell(cell);
    }

    /**
     * 创建条形码
     *
     * @param writer
     * @param barcode  条形码(数字)
     * @param hidnCode 是否隐藏条形码(数字)
     * @return
     */
    public static Image createBarcode(PdfWriter writer, String barcode, Boolean hidnCode) {
        Barcode128 code128 = new Barcode128();
        code128.setCode(barcode);
        // 增加一个条形码到表格
        code128.setCodeType(Barcode128.CODE128);
        // 隐藏文字
        if (hidnCode) {
            code128.setFont(null);
        }
        // 生成条形码图片
        PdfContentByte cb = writer.getDirectContent();
        return code128.createImageWithBarcode(cb, null, null);
    }

    /**
     * 表格添加条形码图片
     *
     * @param table
     * @param lineNum      表格占几列 setRowspan : 设置行
     * @param height       左边距
     * @param height       右边距
     * @param height       高度
     * @param code128Image 条形码图片
     * @return
     */
    public static void setBarcodeCell(PdfPTable table, int left, int right, int lineNum, int height, Image code128Image) {
        // 加入到表格
        PdfPCell cell = new PdfPCell(code128Image, true);
        // 设置左右边距
        if (left > 0) {
            // 左边距
            cell.setPaddingLeft(left);
        }
        if (right > 0) {
            // 右边距
            cell.setPaddingRight(right);
        }
        // 设置行数
        cell.setColspan(lineNum);
        // 边框颜色
        cell.setBorderColor(BaseColor.BLACK);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        // 高度
        cell.setFixedHeight(height);
        table.addCell(cell);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柠檬不萌c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值