Este artículo comparte el código específico de Java que combina imágenes en archivos PDF para su referencia. El contenido específico es el siguiente
Diagrama de interfaz de programa:
Lista de código:
El paquete combina imágenes en archivos PDF; import java.awt.event.ActionEvent; import java.awt.event.actionListener; import java.io.file; import java.io.fileFilter; import java.io.fileOutputStream; import java.io.ioexception; import javax.swing.jbutton; import javax.swing.jfilecooser; javax.swing.jframe; import javax.swing.jlabel; import javax.swing.JOptionPane; import javax.swing.jpanel; import javax.swing.jtextfield; import javax.swing.filechooser.filenameStensionFilter; import Com.ithtpdf.text.Document; importar; com.ithtpdf.text.documentException; import com.ithtpdf.text.image; import com.ithtpdf.text.pagesize; import com.ithtpdf.text.pdf.pdfwriter;/ * * dibujar la interfaz principal y manejar la clase de botones de botones - jiemian_main * * * */class jiemian_mian Extends Jframe Jframe SerialVersionUid = 1657254256189721759L; String privado final shuoming = "Instrucciones para su uso: la función principal de este programa es escalar los grupos de imágenes en el mismo archivo PDF en proporción. ―Winmin"; private String dir_open = "; privado string dir_save =" "; público jframe jf = nill; privado jpanel Jpanel; privado JBUTR; jb_open = null; private jButton jb_save = null; private jButton jb_ok = null; privado jtextfield jt_dir_open = null; private jtextfield jt_dir_save = null; private jlabel jl_dir_open = null; privado jlabel jl_dir_dirave = null jlabel jl_lujing_open = null; private jlabel jl_lujing_save = null; private jTextfield jtf = null; public jiemian_mian () {jf = new jframe ("combinando imágenes en archivos pdf"); jp = new jpanel (); jp.setLayout (null);/*tag*/jl_di JLabel("Please select the folder where the image group is located: ");jl_dir_save = new JLabel("Please select the synthesis location of the PDF: ");jl_lujing_open = new JLabel("Path: ");jl_lujing_save = new JLabel("Path: ");jl_dir_open.setBounds(50, 50, 200, 20); jl_dir_save.setBounds (420, 50, 200, 20); jl_lujing_open.setBounds (50, 80, 40, 20); jl_lujing_save.setBounds (420, 80, 40, 40, 20); jp.add (jl_dir_open); jp.add (jl_dir_save); jp.add (jl_lujing_open); jp.add (jl_lujing_save);/*botón*/jb_open = new jbutton ("browse"); jb_save = new jbutton ("") = nuevo JButton ("Start Synthesis"); jb_open.setBounds (230, 80, 65, 20); jb_save.setBounds (600, 80, 65, 20); jb_ok.setBounds (310, 165, 90, 30); jb_open.addactionListener (new Open (); Save ()); jb_ok.addactionListener (new Start ()); jp.add (jb_open); jp.add (jb_save); jp.add (jb_ok);/*Text de una línea de una sola JTextField (); jt_dir_open.setBounds (90, 80, 130, 20); jt_dir_save.setBounds (460, 80, 130, 20);jt_dir_open.setEditable(false);jt_dir_save.setEditable(false);jp.add(jt_dir_open);jp.add(jt_dir_save);/*Textbox (Instructions for use)*/jtf = new JTextField(shuoming);jtf.setBounds(50,225, 615, 50); jtf.setEnabled (falso); jp.add (jtf);/*main caja*/jf.add (jp); jf.SetSize (715,315) ActionListener {public void ActionPerformed (ActionEvent E) {Lujing_get lujing_get = new Lujing_get (jf); // Cree lujing_get Object y obtenga la ruta del grupo de imágenes dir_open = lujing_get.open_get (); jt_dir_open.settex Ubicación generada por el PDF*/private clase Save implementa ActionListener {public void ActionPerformed (ActionEvent E) {Lujing_get Lujing_get = new Lujing_get (jf); // Crear objeto lujing_get y obtiene la ruta para guardar la ubicación generada por el PDF Dir_save = = lujing_get.save_get (); jt_dir_save.settext (dir_save);}}/*Procesamiento de eventos de troncal para sintetizar PDF*/privado clase begin implementa ActionListener {public void ActionperFormed (ActionEvent E) {/*manejar con precisión la ruta adquirida*/if (dir_save.equals (") ||") dir_open.equals ("")) {jOptionPane.showMessEdialog (jf, "Por favor ingrese la ruta del grupo de imágenes y la ruta de guardado del pdf", "advertencia", joptionPane.warning_message);} else {file_deal fd = new_deal (dir_open); // crea archion_deal Object to Load to Load to Load to Load to Loop sendy to Loag stat if (fd.files ()! = null) {/*manejar con precisión las reglas de nomenclatura (eliminar el nombre del sufijo)*/if (dir_save.lastIndexof (".")! = (-1)) dir_save = dir_save.substring (0, dir_save.lastIndexof (".")); Wm_creatpdf (fd.files (), dir_save); // crea wm_creatpdf objeto para generar pdftry {pdf_creat.creatpdf (); // synthesize pdf file} catch (documentException e1) {// TODO generado automáticamente el bloque e1.printstack) {// TODO Generado automáticamente el bloque de captura e1.printStackTrace ();} jOptionPane.ShowMessEdialog (JF, "Archivo PDF sintetizado, ubicación:"+dir_save+". PDF", "Complete", JOptionPane.Plain_Message);} más jopeTePane.ShowMesedialog (Jef, no hay esta imagen en el archivo de Jess. carpeta (.jpg/.png/.bmp/.tif)! "," advertencia ", joptionPane.warning_message);}}}} class lujing_get {private jframe jf = null; public lujing_get (jframe jf) {this.jf = jf;} String Open_get () ""; Jfilechooser jfc = new jfilechooser (); // Cree el objeto "Seleccione Archivo de archivo" JFC.SetDialogTitle ("Seleccione la carpeta donde el grupo de imágenes está"); Jfc.SetFileSelectionMode (jfilechooser.directories_only); int retras jfc.showopendialog (jf); if (jfilechooser.approve_option == returnval) {dir = jfc.getSelectedFile (). toString ();} return dir; // return ruta} public String save_get () {String dir = ""; jfilechooser jfc = new jfilechooser (); // Cree el objeto "Seleccionar el navegador de archivos" Jfc.SetDialogTitle ("Seleccione la ubicación de síntesis de PDF"); FileMeextensfilter Filter = NUEVO NEW FilenameExtensionFilter ("pdf", "pdf"); jfc.setfileFilter (filtre); int returnval = jfc.showsavedialog (jf); if (jfilechooser.approve_option == returnval) {dir = jfc.getSelectedFile (). Tostring ();} return dir; // return ruta}}/ * * Obtenga el archivo de imagen * * */class file_deal {private string dir_open = ""; public file_deal (string dir_open) {this.dir_open = dir_open;} public file [] files () {file f = new File (dir_open); file fs [] = f.listfiles (newOfilefilfilterfilter ();); 0) return fs; elsereturn null;}}/ * * * filtro de archivo, devuelve el archivo de formato de imagen en el directorio * */class PhotofileFilter implementa FileFilter {@OverridePublic Boolean Acept (File File) {// TODO Automático Generado Método if (File.IsDirectory ()) return False; else {String name = file.getName (); if (name.endswith (". jpg") || name.endswith (". png")) return true; elseif (name.endSwith (". Bmp") || name.endswith (". tif")) return true; elsereturn false;}}}/ * * Generar PDF file (esta clase requiere referencia externa a "it it" it it "it it", it it ", it it", it it ", it it", it it ", it it", it it ", doextf.JarStf.JART.JART.JART. IS: http://www.java2s.com/code/jar/i/i/iithtpdf.htm) * * */class wm_creatpdf {final privado flotante a4_weight = 595-60; // El ancho del estándar A4 FLOAT FINAL A4_HEight = 842-60; // el archivo privado alto [] NEWTH A4 FINAL A4 A4_HEIGHT = 842-60; // El archivo privado alto [] NEUCHO; cadena privada dir_save = ""; public wm_creatpdf (archivo [] archivos, cadena dir_save) {this.files = archivos; this.dir_save = dir_save;} public void creatpdf () lanza documentException, ioException {document document = new Document (pageSize.a4,30,30,30,30,30); // Crear contenedor de documento pdfwriter.getInstance (documento, nuevo archivoutputStream (dir_save+". PDF")); // CREAT contenedor float porcenter = 100; float w, h; for (int i = 0; i <files.length; i ++) {image img = image.getInstance (archivos [i] .getCanonicalPath ());/*Process Image Scaling*/w = img.getWidth (); H = img.gethEight (); if ((w> a4_weight) (A4_weight*100)/w; elseif ((w <a4_weight) && (h> a4_height)) porcentar = (a4_height*100)/h; elseif ((w> a4_weight) && (h> a4_height)) {porcenter = (a4_weight*100)/w; h = h*porcentaje)/100; if (h> a4_height) (A4_height*100)/h;} img.scalePercent (porcentaje); document.add (img);} document.close (); // Cerrar el contenedor} public static void main (string [] args) {// todo automático método generado stub new jiemian_mian ();}} Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.