Este artigo compartilha o código específico de Java combinando imagens em arquivos PDF para sua referência. O conteúdo específico é o seguinte
Diagrama de interface do programa:
Lista de códigos:
O pacote combina imagens em arquivos PDF; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar java.io.file; importar java.io.filefilter; importar java.io.fileoutstream; import java.io.ioxception; import javax.eeching.ermportton; import.mport; javax.swing.jframe; importar javax.swing.jlabel; importar javax.swing.JOptionPane; importar javax.swing.jpanel; importar javax.swing.jtextfield; import javax.swing.filechooser.filenamextfilter; import.ithtpdpdpdpd.filechooser.filenamesxterfilter; import.ithtpdpdpdpd.filechooser.filenamesxterfilter; comb.ithtpd.swing.filechooser.Filenome com.ithtpdf.text.DocumentException;import com.ithtpdf.text.Image;import com.ithtpdf.text.PageSize;import com.ithtpdf.text.pdf.PdfWriter;/* * Draw the main interface and handle button event class - Jiemian_main * * */class Jiemian_mian extends JFrame{private static final long Serialversionuid = 1657254256189721759L; Final Private String string shuoming = "Instruções para uso: A principal função deste programa é escalar os grupos de imagens para o mesmo arquivo PDF na proporção. jb_open = null; private jbutton jb_save = null; private jbutton jb_ok = null; private jtextfield jt_dir_open = null; private jtextfield jt_dir_save = null; private jlabel jl_dir_open = null; private JLabel_dir; jl_lujing_open = null; private jlabel jl_lujing_save = null; private jtextfield jtf = null; public jiemian_mian () {jf = new jframe ("combinando fotos em arquivos pdf"); Jlabel ("Selecione a pasta em que o grupo de imagens está localizado:"); jl_dir_save = new jlabel ("Selecione o local de síntese do pdf:"); jl_lujing_open = new jlabel ("Path:"); 200, 20); jl_dir_save.setbounds (420, 50, 200, 20); jl_lujing_open.setbounds (50, 80, 40, 20); 20); jp.add (jl_dir_open); jp.add (jl_dir_save); jp.add (jl_lujing_open); jp.add (JL_LUJING_SAVE);/*button*/jb_open = New Jbutton ("Brrowse"); = novo jbutton ("Startes de início"); jb_open.setbounds (230, 80, 65, 20); jb_save.setbounds (600, 80, 65, 20); jb_ok.ActActListner (310, 165, 90); Salvar ()); jb_ok.addactionListener (new Begin ()); jp.add (jb_open); jp.add (jb_save); jp.add (jb_ok);*texto de linha única (exibição do caminho)*/jt_dir_open = new jtextfield (); 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 (instruções para uso)*/jtf = new JTextfield (shuoming); 50); jtf.setEnabled (false); jp.add (jtf);/*main box*/jf.add(jp);jf.setSize(715,315);jf.setResizable(false);jf.setLocationRelativeTo(null);jf.setVisible(true);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}/*Button event processing to get the image path*/private class Open implements ActionListener{public void actionPerformed(ActionEvent e){Lujing_get lujing_get = new Lujing_get(jf);//Create Lujing_get object and get the image group path dir_open = lujing_get.open_get();jt_dir_open.setText(dir_open);}}/*Get button event processing that selects the path to save A localização gerada pela classe PDF*/privada Salvar implementos ActionListener {public void ActionPerformed (ActionEvent E) {lujing_get lujing_get = new Lujing_get (JF); // Crie Lujing_get Objeto e obtém o caminho para salvar o local gerado pelo PDF Dir_Save = lujing_get.save_get (); jt_dir_save.settext (dir_save);}}/*Processamento de eventos de tronco para sintetizar PDF*/classe privada iniciar implementa ActionListener {public void de acordo com (açãoeVent e) {/*" dir_open.equals ("")) {JoptionPane.ShowMessAgedialog (JF, "Por favor, digite o caminho do grupo de imagens e o caminho de salvamento do PDF", "Warning", JOptionPane.warning_message);} else {file_deal fd = new File_Deal (_open); if (fd.files ()! = null) {/*lida com precisão Regras de nomeação de PDF (remova o nome do sufixo)*/if (dir_save.LastIndexof (".")! = (-1)) DIR_SAVE = DIR_SAVE.SUBSTRING (0, DIR_SAVE.LASTINDEXOF (". Wm_creatpdf (fd.files (), dir_save); // crie objeto wm_creatpdf para gerar pdftry {pdf_creat.creatpdf (); // synthesize pdf file} catch (documentException e1) {// Todo gerado automaticamente o chap TODO gerou automaticamente o bloco de captura e1.printStackTrace ();} JoptionPane.showMessAgedialog (JF, "Arquivo PDF sintetizado, Localização:"+DIR_SAVE+". PDF", "Complete", JoptionPane.Plain_Message);} mais (.jpg/.png/.bmp/.tif)! "," Warning ", joptionpane.warning_message);}}}} classe lujing_get {private jframe jf = null; public lujing_get (jframe jf) {this.jf = jf; jfc = new jfileChooser (); // Crie o objeto "Selecionar navegador" do objeto jfc.setDialogtitle ("Selecione a pasta onde o grupo de imagens é"); jfc.setFileSelectionMode (jfilechooser.Directories_only); Int ReturnVal = jfowondialial == returnVal) {dir = jfc.getSelectedFile (). ToString ();} retornar dir; // Caminho de retorno} public string save_get () {string dir = ""; jfilechooser jfc = new jfileChooser (); // Crie o "Selecione o navegador de arquivo" JFC.setDialogtitle ("Por favor, selecione a localização da síntese do PDF"); FILENOMEXTIMFILTER FILTER = = FilenameextensionFilter ("pdf", "pdf"); jfc.setfilefilter (filtro); int returnVal = jfc.showsAvedialog (jf); if (jfilechooser.approve_option == return) {Dir =} // Caminho de retorno}}/ * * Obtenha o arquivo de imagem * * * */classe 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 Photo_open); file fs [] fs [] f.lists [] files () {file f = new File (DIR_OPEN); FRIGHTFS [] 0) Retornar FS; elsereturn null;}}/ * * * Filtrar, retornar o arquivo de formato de imagem no diretório * */class PhotofileFilter implementa o FileFilter {@OverridePublic boolean Acepty (arquivo de arquivo) {// TODO Método gerado automático) file.getName (); if (name.endswith (". jpg") || name.endswith (". O endereço é: http://www.java2s.com/code/jar/i/i/iithtpdf.htm) * * */classe wm_creatpdf {flutuação privada final a4_eight = 595-60; // a largura do padrão a4 final privado a4_height = 82-2-60; private string dir_save = ""; public wm_creatpdf (arquivos de arquivo [], string dir_save) {this.files = files; this.dir_save = dir_save;} public void cretpdf () lança documentException, ioexception {document document = new Document (Pagesize.A4,30,30,30,30); // Criar Document Container.TerpTer.getInstance (Novo FileOutstream (Dir_aNave+". Float por cento do contêiner = 100; flutuador w, h; para (int i = 0; i <files.length; i ++) {imagem img = image.getInstance (arquivos [i] .getCanonicalPath ());/*Processe a imagem da imagem*/w = img.getwidth (); h = img.getheight () se; (A4_eight*100)/w; elseif ((w <a4_weight) && (h> a4_height)) porcent = (a4_height*100)/h; elseif ((w> a4_weight) && (h> a4_Height)) { % = (a4_eight*100)/w; h (h) (A4_Height*100)/h;} img.ScalePercent (porcentagem); document.add (img);} document.close (); // feche o contêiner} public static void main (string [] args) {// TODO Método gerado automático Stub Novo jiemian_mian ();}}} O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.