Java 网络PDF转图片

照旧是总结前人的技术

show code!

一 依赖

<!--PDF转换为图片-->
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>fontbox</artifactId>
    <version>2.0.1</version>
</dependency>
<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>pdfbox</artifactId>
   <version>2.0.1</version>
</dependency>

二 代码

    public void pdfToImg(HttpServletResponse response ,String pdfUrl) {
        String imageType = "PNG";//可改成JPG
        OutputStream sos = null;
        try {
            sos = response.getOutputStream();
            PDFToImg(sos, pdfUrl, getPDFNum(pdfUrl), imageType);
            sos.flush();
        } catch (Exception e) {
            log.error("PDF转换图片异常: " + e.getMessage());
            throw new RuntimeException("PDF转换异常");
        } finally {
            try {
                sos.close();
            } catch (IOException e) {
                log.error("关闭输出流异常: " + e.getMessage());
            }
        }
    }

    /**
     * PDF转图片 根据页码一页一页转
     * @throws IOException
     * imgType:转换后的图片类型 jpg,png
     */
    private void PDFToImg(OutputStream sos,String fileUrl,int page,String imgType) throws Exception {
        PDDocument pdDocument = null;
        /* dpi越大转换后越清晰,相对转换速度越慢 */
        int dpi = 100;
        try {
            pdDocument = getPDDocument(fileUrl);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            int pages = pdDocument.getNumberOfPages();
            if (page <= pages && page > 0) {
                BufferedImage image = renderer.renderImageWithDPI(page-1,dpi);
                ImageIO.write(image, imgType, sos);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
            throw new RuntimeException("PDF转换异常");
        } finally {
            if (pdDocument != null) {
                pdDocument.close();
            }
        }

    }

    private PDDocument getPDDocument(String fileUrl) throws IOException {
        InputStream inputStream = getInputStreamByUrl(fileUrl);
        return PDDocument.load(inputStream);
    }


    /**
     * 根据url地址 获取输入流
     * @param url
     * @return
     * @throws IOException
     */
    private InputStream getInputStreamByUrl(String url) throws IOException {
        URL httpurl=new URL(URLDecoder.decode(url, "UTF-8"));
        InputStream is;
        HttpURLConnection httpConn=(HttpURLConnection)httpurl.openConnection();
        httpConn.setDoOutput(true);// 使用 URL 连接进行输出
        httpConn.setDoInput(true);// 使用 URL 连接进行输入
        httpConn.setUseCaches(false);// 忽略缓存
        httpConn.setRequestMethod("GET");// 设置URL请求方法
        //可设置请求头
        httpConn.setRequestProperty("Content-Type", "application/octet-stream");
        httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        httpConn.setRequestProperty("Charset", "UTF-8");
        httpConn.connect();
        if (httpConn.getResponseCode() >= 400 ) {
            is = httpConn.getErrorStream();
        }
        else{
            is = httpConn.getInputStream();
        }
        return is;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,我们可以通过使用外部库来将二进制数据换为PDF格式。其中一个常用的库是Apache PDFBox。 首先,你需要将二进制数据读入到Java程序中。可以使用FileInputStream类读取文件中的二进制数据,也可以使用InputStream类从网络中获取二进制数据。 一旦你获得了二进制数据,你可以使用PDFBox库来创建一个PDF文档。你可以使用PDFDocument类创建一个新的文档对象,并使用addPage方法向文档中添加页面。 接下来,你需要将二进制数据换为PDF页面内容。你可以使用PDFBox提供的各种方法来添加文本、图像、表格等内容到PDF页面中。 最后,你可以使用PDFDocument的save方法将PDF文档保存到文件输出流中。你可以指定保存的文件名,或者可以将输出流连接到任何地方,如网络或数据库。 以下是一个简单的示例代码,使用Apache PDFBox将二进制数据换为PDF: ```java import org.apache.pdfbox.pdmodel.PDDocument; import java.io.ByteArrayInputStream; import java.io.FileOutputStream; import java.io.IOException; public class BinaryToPdfConverter { public static void main(String[] args) { byte[] binaryData = /* 读取二进制数据到字节数组 */; try (PDDocument document = new PDDocument()) { document.addPage(new PDPage()); // 添加二进制数据到页面中,例如添加一张图片 PDImageXObject image = PDImageXObject.createFromByteArray( document, binaryData, "image"); PDPageContentStream contentStream = new PDPageContentStream(document, document.getPage(0)); contentStream.drawImage(image, 100, 100); contentStream.close(); // 保存PDF文件 document.save("output.pdf"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码将二进制数据作为图片添加到PDF页面中,并将生成的PDF文档保存为"output.pdf"文件。 请注意,这只是一个基本的示例,你可以根据实际需求使用PDFBox库进行更复杂的操作和排版。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值