В этой статье используется конкретный код Java, объединяющий изображения в PDF -файлы для вашей ссылки. Конкретный контент заключается в следующем
Диаграмма интерфейса программы:
Список кода:
Пакет объединяет изображения в файлы PDF; Импорт java.awt.event.actionevent; import java.awt.event.actionlistener; импорт java.io.file; import java.io.filefilter; импорт java.io.fileoutputstream; импорт java.io.ioexception; импорт javax.swing.jbutton; import javax.swing.jfilech javax.swing.jframe; import javax.swing.jlabel; import javax.swing.joptionpane; import javax.swing.jpanel; импорт javax.swing.jtextfield; импорт javax.swing.filechoser.filenameextension; com.ithtpdf.text.documentexception; import com.ithtpdf.text.image; import com.ithtpdf.text.pagesize; import com.ithtpdf.text.pdf.pdfwriter;/ * * Нарисуйте основной интерфейс и кнопку 1657254256189721759L; Окончательная частная строка shumoming = " 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 jl_dir_save = null; private jlabel = null; private jlabel jl_dir_save = null; private jlabel = null. Jlabel jl_lujing_save = null; private jtextfield jtf = null; public jiemian_mian () {jf = new jframe («Объединение изображений в файлы pdf»); jp = new jpanel (); jp.setlayout (null);/*tag*/jl_dir_open = new jlab (null);/*tag*jl_dir_open = new Jlab (null); "); jl_dir_save = new jlabel (« Пожалуйста, выберите место синтеза PDF: "); jl_lujing_open = new jlabel (" path: "); jl_lujing_save = new jlabel (" path: "); jl_dir_open.setbounds (50, 50, 200, 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, 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 ("browse"); = new 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.AdactionListener (new Open (); Save ()); jb_ok.addactionListener (new Begin ()); jp.add (jb_open); jp.add (jb_save); jp.add (jb_ok);/*однострочный текст (Path Display)*/jt_dir_open = new jtextfield (); jt_dir_save = new 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 (false); jp.add (jtf);/*main Box*/jf.add (jp); jf.setsize (715,315); jf.setReSizeable (false); jf.setLocationRelativeTo (null); jf.setvisible (true); Jf.setDefaultCloseoperation (Jframe.Exit_Close); ActionListener {public void ActionPerformed (actionEvent e) {lujing_get lujing_get = new lujing_get (jf); // Создать объект lujing_get и получить путь группы изображений dir_open = lujing_get.open_get (); jt_dir_open.settext (dir_open); Местоположение, сгенерированное PDF*/Private Class Save Save Likerslistener {public void actionPerformed (actionEvent e) {lujing_get lujing_get = new lujing_get (jf); // Создание объекта lujing_get и получает путь, чтобы сохранить местоположение, сгенерированное PDF dir_save = lujing_get.save_get (); jt_dir_save.settext (dir_save);}}/*Обработка событий багажника для синтеза pdf*/private class Начало реализует ActionListener {public void Actionperfored (ActionEvent e) {/*Точно обрабатывает приобретенный путь*/if (dir_save.eavals ("") dir_open.equals("")){JOptionPane.showMessageDialog(jf, "Please enter the path of the image group and the PDF's saving path", "Warning", JOptionPane.WARNING_MESSAGE);}else{File_deal fd = new File_deal(dir_open);//Create File_deal object to load all image files in the image group path accurately if (fd.files ()! = null) {/*Точно обрабатывать правила именования PDF (удалить имя суффикса)*/if (dir_save.lastIndexof (".")! = (-1)) dir_save = dir_save.substring (0, dir_save.lastIndexof (". Wm_creatpdf (fd.files (), dir_save); // Создать объект wm_creatpdf для генерации pdftry {pdf_creat.creatpdf (); // synthize pdf file} catch (documentexception e1) {// todo автоматически сгенерированный catch block e1.printcktrace () {// todo автоматически сгенерированный catch block e1.printc TODO автоматически сгенерированный блок Catch E1.printStackTrace ();} joptionPane.showMessageDialog (JF, «синтезированный файл PDF, местоположение:"+dir_save+". Pdf", "Complete", JoptionPane.plain_Message); (.jpg/.png/.bmp/.tif)! »," Warning ", JoptionPane.warning_message);}}}} класс lujing_get {private jframe jf = null; public lujing_get (jframe jf) {this.jf = jf;} public string_get (jframe jf) {this.jf = jf;} open_get () {string = string (jframe jf) {this.jf = jf;} open_get () {string_get () {string_get (jframe jf). jfc = new jfilechooser (); // Создать «Select File Browser» Object jfc.setDialogTitle («Пожалуйста, выберите папку, в которой группа изображений -»); jfc.setFileSelectionMode (jfilechooser.directories_only); int returnVal = jfc.showopendialog (jfiprectore. returnVal) {dir = jfc.getSelectedFile (). toString ();} return dir; // возвращаемый путь} public String save_get () {string dir = ""; JFileChooser jfc = new jfileChooser (); // Создать «Select File Browser» Object JFC.SetDialogTitle («Пожалуйста, выберите место синтеза PDF»); FileNameExtensionFilter ("pdf", "pdf"); jfc.setfilefilter (filter); int returnval = jfc.showsavedialog (jf); if (jfilechooser.approve_option == returnval) {dir = jfc.getselectedfile (). // возвращение пути}}/ * * Получить файл изображения * * */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); fis fis [] = f.listfiles (new Photlefilithlithlithlithlithlithfilithlithlithlithlithlithlithlithlithlithlithlithlithlithlithlithlithlithlithlith 0) return fs; elsereturn null;}}/ * * * Файл -фильтр вернуть файл формата изображения в каталоге * */class photofilefilter реализует FileFilter {@OverridePublic Boolean Accept (файл файл) {// TODO автоматически сгенерированный метод. file.getName (); if (name.endswith (". jpg") || name.endswith (". png")) return true; elseif (name.endswith (". bmp") || name.endswith (". tif")) return true; elsereturn false;}}/ * * * * * * * * * * * * * * * * * * * * Адрес: http://www.java2s.com/code/jar/i/i/iithtpdf.htm) * * * */class wm_creatpdf {final private a4_weight = 595-60; // Ширина стандартного A4 Final Private Float A4_Height = 842-60; // Высоковатный файл; Приватная строка dir_save = ""; public wm_creatpdf (file [] files, string dir_save) {this.files = files; this.dir_save = dir_save;} public void createpdf () throws DocumentException, ioException {Document Document = новый документ (pagesize.a4,30,30,30,30); // Создать контейнер документа pdfwriter.getinstance (документ, новый файловый тип (dir_save+». document.open (); // Открыть контейнер float procet = 100; float w, h; for (int i = 0; i <files.length; i ++) {image img = image.getInstance (files [i] .getCanonicalPath ());/*Масштабирование процесса*/w = w = w = wweed (); A4_height)) процент = (a4_weight*100)/w; elseif ((w <a4_ween) && (h> a4_height)) процент = (a4_height*100)/h; elseif ((w> a4_weight) && (h> a4_height)) {процент = (a4_ -weight*100)/w; h*h> (h> (h> h/h/h/h/h/h/h/h. A4_Height) процент = (A4_Height*100)/h;} img.scalepercent (процент); document.add (img);} document.close (); // Закрыть контейнер} public static void main (string [] args) {// todo Automatic Genedered Method New Jemian_mian (); Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.