This article describes the method of implementing screenshots of pdf files in Java. Share it for your reference, as follows:
In a website I recently built, there is a requirement to upload a pdf file, display the pdf cover page, and then click the cover page to read online. Here, PDFRender is used to take screenshots of pdf.
public static boolean createScreenShoot(String source, String target) { File file = new File(source); if (!file.exists()) { System.err.println("Path[" + source + "] corresponding pdf file does not exist!"); return false; } try{ RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); int num = pdffile.getNumPages(); for(int i = 1; i < num; i++){ PDFPage page = pdffile.getPage(1); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle(0, 0, (int) page.getBBox() .getWidth(), (int) page.getBBox().getHeight()); // generate the image Image img = page.getImage(rect.width, rect.height, // width & rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,null); FileOutputStream out = new FileOutputStream(target+i+"jpg"); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); // JPEG encoding out.close(); } return true; } catch(Exception e){ e.printStackTrace(); return true; }In addition, if you need to display the pdf online, you need to set the response header
response.setContentType("application/pdf");Attachment: pdfRender.jar Click here to download this site .
For more Java-related content, readers who are interested in this site can view the topics: "Summary of Java Image Operation Skills", "Summary of Java Date and Time Operation Skills", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Tutorials of Java Data Structure and Algorithm".
I hope this article will be helpful to everyone's Java programming.