This article shares the specific code for Java to convert Img and PDF to each other for your reference. The specific content is as follows
If you are not good at expressing, just post the code directly. Please ignore me.
import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import com.Utils.ImgFileTool; import com.lowagie.text.Document; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfCopy; import com.lowagie.text.pdf.PdfImportedPage; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfWriter; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import com.sun.pdfview.PDFFile; import com.sun.pdfview.PDFPage; /** * * @author hubiao * @dateTime 2014-06-07 * This tool implements the mutual conversion of IMG and PDF. * To run the test, you need to import the following 2 jar packages* itext-2.0.2.jar * PDFRenderer.jar * */ @SuppressWarnings("unused") public class ImgPdfUtils { public static void main(String[] args) throws Exception { //PDF package extract pdf //pdfExtraction(); //pdf to jpg //pdfToJpg("E://java//data pdf//1.pdf","E://java//data pdf//1.jpg",1); //Combine multiple jpgs directly into pdf packages//extractionPdf("F://temp//Project//Data//dfdsfds//Paris Commune Activist's Biography_img","F://temp//Project//Data//dfdsfds//Paris Commune Activist's Biography_img.pdf"); //jpg to pdf //jpgToPdf(); //File sorting//listOrder(); ImgFileTool.imgMerageToPdf(new File("F://temp//Project//Data//dfdsfds//Paris Commune Activist's Biography_img").listFiles(), new File("F://temp//Project//Data//dfdsfds//","Parised Activists in Paris.pdf")); } private static void listOrder() { File[] listFiles = new File("F://temp//Project//Data//dfdsfds//Parised Activists in Paris_img").listFiles(); TreeMap<Integer, File> tree = new TreeMap<Integer, File>(); for(File f : listFiles) { tree.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f); } for(Entry<Integer, File> eif : tree.entrySet()) { System.out.println(eif.getKey()+"="+eif.getValue().toString()); } } /** * @param list Image collection* @param file Save path* @return true, merge is completed* If the file name is not 1.jpg, 2.jpg, 3.jpg, 4.jpg. You need to rewrite the sorting method of TreeMap by yourself! */ public static boolean imgMerageToPdf(File[] list, File file)throws Exception { //1: Naturally sort the image files by name through TreeMap Map<Integer,File> mif = new TreeMap<Integer,File>(); for(File f : list) mif.put(Integer.parseInt(f.getName().replaceAll(".jpg$", "")), f); //2: Get the width and height of the first Img as the standard for PDF documents ByteArrayOutputStream baos = new ByteArrayOutputStream(2048*3); InputStream is = new FileInputStream(mif.get(1)); for(int len;(len=is.read())!=-1;) baos.write(len); baos.flush(); Image image = Image.getInstance(baos.toByteArray()); float width = image.width(); float height = image.height(); baos.close(); //3: Instantiate PDF document object through width and height. Document document = new Document(new Rectangle(width,height)); PdfWriter pdfWr = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); //4: Get each image file and convert it into an IMG object. Load into Document object for(Entry<Integer,File> eif : mif.entrySet()) { //4.1: Read into memory baos = new ByteArrayOutputStream(2048*3); is = new FileInputStream(eif.getValue()); for(int len;(len=is.read())!=-1;) baos.write(len); baos.flush(); //4.2 Generate IMG object through byte byte image = Image.getInstance(baos.toByteArray()); Image.getInstance(baos.toByteArray()); image.setAbsolutePosition(0.0f, 0.0f); //4.3: Add to document.add(image); document.newPage(); baos.close(); } //5: Release the resource document.close(); pdfWr.close(); return true; } /** * * @param source source file* @param target target file* @param x Read the page in the source file*/ private static void pdfToJpg(String source,String target,int x) throws Exception { //Create a random access file stream from and writes (optional) to it. R means that it is just an access mode to it. RandomAccessFile rea = new RandomAccessFile(new File(source), "r"); //Read the stream into memory and then map a PDF object FileChannel channel = rea.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,0, channel.size()); PDFFile pdfFile = new PDFFile(buf); PDFPage page = pdfFile.getPage(x); // get the width and height for the doc at the default zoom java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page.getBBox() .getWidth(), (int) page.getBBox().getHeight()); // generate the image java.awt.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); // Output to file stream JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); // JPEG encoding out.close(); } /** * @param source Source PDF file path* @param target Save PDF file path* @param pageNum Extract the pageNum page in PDF* @throws Exception */ private static void pdfExtraction(String source,String target,int pageNum) throws Exception{ //1: Create PDF reading object PdfReader pr = new PdfReader(source); System.out.println("this document "+pr.getNumberOfPages()+" page"); //2: Convert the page page to extract and create the document object Document doc = new Document(pr.getPageSize(pageNum)); //3: Convert it to store it separately through PdfCopy PdfCopy copy = new PdfCopy(doc, new FileOutputStream(new File(target))); doc.open(); doc.newPage(); //4: Get the first page and load it into the document. PdfImportedPage page = copy.getImportedPage(pr,pageNum); copy.addPage(page); //5: Release the resource copy.close(); doc.close(); pr.close(); } /** * @param pdfFile Source PDF file* @param imgFile Picture file*/ private static void jpgToPdf(File pdfFile,File imgFile) throws Exception { //File to img InputStream is = new FileInputStream(pdfFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); for(int i;(i=is.read())!=-1;) { baos.write(i); } baos.flush(); //Get the width and height of the image. Image img = Image.getInstance(baos.toByteArray()); float width = img.width(); float height = img.height(); img.setAbsolutePosition(0.0F, 0.0F);//Cancel Offset System.out.println("width = "+width+"/theight"+height); //img to pdf Document doc = new Document(new Rectangle(width,height)); PdfWriter pw = PdfWriter.getInstance(doc,new FileOutputStream(imgFile)); doc.open(); doc.add(img); //Release the resource System.out.println(doc.newPage()); pw.flush(); baos.close(); doc.close(); pw.close(); } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.