网络图片转PDF, // pngPath :网络图片地址 PdfUtilImgUtil pu= new PdfUtilImgUtil(); // 获取证书编号 String imageName= redisUtil.get(CacheConstants.CACHE_CERT_TEMP+qcr.getId()); //创建临时文件 File upload= null; try { upload = File.createTempFile(imageName,".pdf"); } catch (IOException e) { log.error("创建临时文件失败",e); } pu.imgOfPdf(pngPath,upload);

PDF转图片:

//pdfUrl :PDF网络地址 PdfUtilImgUtil pu= new PdfUtilImgUtil(); File imgFIle= null, pdf=null; try { imgFIle = File.createTempFile(RandomUtil.randomNumbers(16),".png"); pdf = pu.getFile(pdfUrl); } catch (Exception e) { e.printStackTrace(); } pu.pdfToImage(pdf,imgFIle);

		PdfUtilImgUtil.java如下:
		
		package com.wafer.utils;

import java.awt.image.BufferedImage; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList;

import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest;

import cn.hutool.Hutool; import cn.hutool.core.img.ImgUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RandomUtil; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import com.wafer.global.Const; import lombok.extern.slf4j.Slf4j; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer;

/**

  • @ClassName PdfUtilImgUtil

  • @Description TODO

  • @Author 田剑

  • @Date 2021/3/1 14:48 */ @Slf4j public class PdfUtilImgUtil { public static File Pdf(ArrayList<String> imageUrllist, File mOutputPdfFileName) { Document doc = new Document(PageSize.A4, 20, 20, 20, 20); //new一个pdf文档 try { PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); //pdf写入 doc.open();//打开文档 for (int i = 0; i < imageUrllist.size(); i++) { //循环图片List,将图片加入到pdf中 doc.newPage(); //在pdf创建一页 Image png1 = Image.getInstance(imageUrllist.get(i)); //通过文件路径获取image float heigth = png1.getHeight(); float width = png1.getWidth(); int percent = getPercent2(heigth, width); png1.setAlignment(Image.MIDDLE); png1.scalePercent(percent + 3);// 表示是原来图像的比例; doc.add(png1); } doc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

    File mOutputPdfFile = mOutputPdfFileName; //输出流 if (!mOutputPdfFile.exists()) { mOutputPdfFile.deleteOnExit(); return null; } return mOutputPdfFile; //反回文件输出流 }

public static 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; }

public static int getPercent2(float h, float w) { int p = 0; float p2 = 0.0f; p2 = 530 / w * 100; p = Math.round(p2); return p; }

public void imgOfPdf(String filepath, File target) { boolean result = false; try { ArrayList<String> imageUrllist = new ArrayList<String>(); //图片list集合 imageUrllist.add(filepath); //添加图片文件路径 String fles = filepath.substring(0, filepath.lastIndexOf(".")); File file = PdfUtilImgUtil.Pdf(imageUrllist, target);//生成pdf file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } }

public void pdfToImage(File pdfFile, File imgFile) { log.info("-----------------------------pdf转PNG--------------------------------------"); long start = System.currentTimeMillis(); try (PDDocument doc = PDDocument.load(pdfFile)) { PDFRenderer renderer = new PDFRenderer(doc); int pageCount = doc.getNumberOfPages(); for (int i = 0; i < pageCount; i++) { // 第二个参数越大生成图片分辨率越高,转换时间也就越长 BufferedImage image = renderer.renderImage(i, 1.25f); ImageIO.write(image, "PNG", imgFile); } long end = System.currentTimeMillis(); log.info("------------------------pdf转PNG完成,用时:" + (end - start) + "ms--------------------------"); } catch (Exception e) { log.error("----------------------pdf转PNG失败,异常信息:" + e.getMessage() + "--------------------------"); } }

/**

  • 将图片转为file
  • @param url 图片url
  • @return File
  • @author dyc
  • date: 2020/9/4 14:54 */ public File getFile(String url) throws Exception { //对本地文件命名 String fileName = url.substring(url.lastIndexOf("."),url.length()); File file = null;
URL urlfile;
InputStream inStream = null;
OutputStream os = null;
try {
  file = File.createTempFile("net_url", fileName);
  //下载
  urlfile = new URL(url);
  inStream = urlfile.openStream();
  os = new FileOutputStream(file);

  int bytesRead = 0;
  byte[] buffer = new byte[8192];
  while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
    os.write(buffer, 0, bytesRead);
  }
} catch (Exception e) {
  e.printStackTrace();
} finally {
  try {
    if (null != os) {
      os.close();
    }
    if (null != inStream) {
      inStream.close();
    }

  } catch (Exception e) {
    e.printStackTrace();
  }
}

return file;

}

// // public static void main(String[] args) { // PdfUtilImgUtil pu =new PdfUtilImgUtil(); // File imgFIle= null, pdf=null; // try { // imgFIle = File.createTempFile("2020/2021-00003",".png"); // pdf = pu.getFile("https://testqe.rd.virsical.cn/res/visitor.com/vst/20210301/afed152d96c4008a3fb5641dfcd7c5a8.pdf"); // } catch (Exception e) { // e.printStackTrace(); // } // pu.pdfToImage(pdf,imgFIle); // System.out.println(imgFIle.getAbsolutePath()); // // }

}