Java pdf和jpg互转

pdfbox: jpg转pdf:

/**
     * 使用pdfbox将jpg转成pdf
     * @param jpgStream jpg输入流
     * @param pdfPath pdf文件存储路径
     * @throws IOException IOException
     */
    public static void jpgToPdf(InputStream jpgStream, String pdfPath) throws IOException {

        PDDocument pdDocument = new PDDocument();
        BufferedImage image = ImageIO.read(jpgStream);

        PDPage pdPage = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
        pdDocument.addPage(pdPage);
        PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, image);
        PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdPage);
        contentStream.drawImage(pdImageXObject, 0, 0, image.getWidth(), image.getHeight());
        contentStream.close();
        pdDocument.save(pdfPath);
        pdDocument.close();
    }

pdfbox: pdf转jpg:

static void pdfbox() throws IOException {
        long start = System.currentTimeMillis();
        //pdf路径
        URL url = new URL("file:///D:/1.pdf");
        InputStream stream = URLUtil.getStream(url);
        // 加载解析PDF文件
        PDDocument doc = PDDocument.load(stream);
        PDFRenderer pdfRenderer = new PDFRenderer(doc);
        PDPageTree pages = doc.getPages();
        int pageCount = pages.getCount();
        for (int i = 0; i < pageCount; i++) {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bim, "jpg", os);
            byte[] datas = os.toByteArray();
//            InputStream is = new ByteArrayInputStream(datas);
            //jpg文件转出路径
            FileUtil.writeBytes(datas, new File("d:/jpg/" + i + ".jpg"));
        }
        long end = System.currentTimeMillis();
        long time = (end - start) / 1000;
        System.out.println(StrUtil.format("pdf转jpg耗时: {}s", time));
    }

icepdf: pdf转jpg

Document document = new Document();
document.setUrl(new URL(pdfUrl));
int pageNum = document.getNumberOfPages();
for (int i = 0; i < pageNum; i++) {
    // 目前仅支持1对1的pdf->jpg
    if (i != 0) {
        continue;
    }
    // 3、pdf -> jpg
    BufferedImage bim = (BufferedImage) document.getPageImage(i,
            GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX,
            rotation, scale);
    os = new ByteArrayOutputStream();
    ImageIO.write(bim, "jpg", os);
    // 4、jpg -> fdfs
    byte[] datas = os.toByteArray();
    InputStream is = new ByteArrayInputStream(datas);
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员青戈

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

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

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

打赏作者

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

抵扣说明:

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

余额充值