itext修改pdf尺寸之后输出为byte格式

本文介绍如何利用iText库修改PDF文件尺寸,并将处理后的PDF转换为Byte数组,强调需避免在方法内部转换,确保完整执行后再获取ByteOutputStream的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写自定义目录标题

itext

注意不要在方法内部转化byte,方法未走完时,byteoutputstream是没有数据的,得到byteoutputstream转化为byte就很方便

    /**
     * @Param source 源文件
     * @Param target 转换后文件
     * @Description 将PDF转为A4格式
     * @Date: 2021/4/25
     **/
    private static ByteArrayOutputStream convert(InputStream inputStream) {
        try {
            PdfReader pdfReader = new PdfReader(inputStream);
            // FileOutputStream out = new FileOutputStream(target);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Document doc = new Document();
            PdfWriter writer = PdfWriter.getInstance(doc, out);
            doc.open();
            PdfContentByte cb = writer.getDirectContent();

            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                PdfImportedPage page = writer.getImportedPage(pdfReader, i);
                float width = page.getWidth();
                float height = page.getHeight();
                if (height > width) {
                    // 横向
                    doc.setPageSize(PageSize.A4);
                    doc.newPage();
                    // 计算比例
                    float widthScale = getWidthScale(width);
                    float heightScale = getHeightScale(height);
                    cb.addTemplate(page, widthScale, 0, 0, heightScale, 0, 0);
                }
                else {
                    // 纵向
                    doc.setPageSize(new com.itextpdf.text.Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()));
                    doc.newPage();
                    float widthScale = getWidthScale(height);
                    float heightScale = getHeightScale(width);
                    cb.addTemplate(page, widthScale, 0, 0, heightScale, 0, 0);
                }

            }
            doc.close();
            writer.close();
            return out;
        }
        catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private static float getWidthScale(float width) {
        float scale = PageSize.A4.getWidth() / width;
        return scale;
    }

    private static float getHeightScale(float height) {
        float scale = PageSize.A4.getHeight() / height;
        return scale;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值