html转pdf,pdf转图片,office转pdf

package com.111.utils;

import java.io.File;

public class HtmlToPdf {
    //wkhtmltopdf在系统中的路径
    private static final String toPdfTool = "c:\\wkhtmltopdf.exe";

public static void main(String[] args) {
        htmltoPDF.convert("https://blog.csdn.net/qq_14873105/article/details/51394026","D:\\tts9\\wkhtmltox\\outFile\\ttt.pdf",toPdfTool);
    };
    /**
     * html转pdf
     * @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath,String mToolPath){
        File file = new File(destPath);
        File parent = file.getParentFile();
        //如果pdf保存路径不存在,则创建路径
        if(!parent.exists()){
            parent.mkdirs();
        }

        if(mToolPath==null){
            mToolPath = toPdfTool;
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(" "+mToolPath);
        cmd.append(" ");
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);

        boolean result = true;
        try{
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        }catch(Exception e){
            result = false;
            e.printStackTrace();
        }
        return result;
    }
}


=============================
package com.111.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 当java调用wkhtmltopdf时,用于获取wkhtmltopdf返回的内容
 */
public class HtmlToPdfInterceptor extends Thread {
    private InputStream is;

    public HtmlToPdfInterceptor(InputStream is){
        this.is = is;
    }

    public void run(){
        try{
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line.toString()); //输出内容
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
=============================
package com.111.utils;

import com.111.plat.PlatformContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * Html转PDF
 */
@WebServlet("/htmltopdf/servlet")
public class HtmlToPdfServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private PlatformContext platContext;
    /**
     * Servlet接收参数path,获取html的url
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getParameter("path");
        if(path == null || path.equals("")){
            return;
        }
        String base="",mPath="";

        try {
            platContext = PlatformContext.getInstance();
            base = (String) platContext.config("app.report.webhtmltopdf.base");
            mPath = (String) platContext.config("app.report.webhtmltopdf.path");
        } catch (Exception e) {

            e.printStackTrace();
        }

        //获取pdf的临时保存路径
        //tmp为网站下的目录
        //把生成的pdf放到网站下以便下载
        Date today = new Date();
        Calendar rightNow = Calendar.getInstance();
        //  String filepath
        String pdfPath = request.getSession().getServletContext().getRealPath("/tmp");
        String pdfName = UUID.randomUUID().toString().replaceAll("\\-", "") + ".pdf";
        String format = String.format("%d/%d/%d/%s",rightNow.get(Calendar.YEAR), rightNow.get(Calendar.MONTH), rightNow.get(Calendar.HOUR_OF_DAY),pdfName);
        if(HtmlToPdf.convert(path, pdfPath+"/"+format,mPath)){
            response.sendRedirect(request.getContextPath() + "/tmp/" + format);
        }
    }
}

=======================
package com.111.utils;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;

import javax.swing.SwingUtilities;

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 DELL
 */
public class PdfToJpg {
    public static void setup() throws IOException {

        // load a pdf from a byte buffer
        File file = new File("D://pri.pdf");
        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);

        System.out.println("页数: " + pdffile.getNumPages());

        BufferedImage tag = null;

        //将图片放入frame中
        //JFrame frame =null;
        //frame的名称
        // frame = new JFrame("PDF Test");
        //JLabel label = null;
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        for (int i = 1; i <= pdffile.getNumPages(); i++) {
            // draw the first page to an image
            PDFPage page = pdffile.getPage(i);
            // 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 &
                    // height
                    rect,
                    // clip rect
                    null,
                    // null for the ImageObserver
                    true,
                    // fill background with white
                    true
                    // block until drawing is done
                    );
            tag = new BufferedImage(rect.width, rect.height,
                    BufferedImage.TYPE_INT_RGB);

            // label = new JLabel(new ImageIcon(img));

            // System.out.println(label);

            tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,
                    null);
            // 输出到文件流
            FileOutputStream out = new FileOutputStream("d://pdfToImg" + i + ".png");

            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);
            // JPEG编码
            out.close();

            //   unmap(buf);
            System.out.println("PDF文件转换JPG文件成功");
            //将label添加给frame
            // frame.add(label);
            // System.out.println(frame);

        }

        channel.close();

        raf.close();

        unmap(buf);
        //如果要在转图片之后删除pdf,就必须要这个关闭流和清空缓冲的方法
        // show the image in a frame
        //frame.pack();
        // frame.setVisible(true);
    }

    /**

     * 清空缓冲

     * @param buffer

     */

    public static void unmap(final Object buffer) {

        AccessController.doPrivileged(new PrivilegedAction() {

            @Override
            public Object run() {

                try {

                    Method getCleanerMethod = buffer.getClass().getMethod(
                            "cleaner", new Class[0]);

                    getCleanerMethod.setAccessible(true);

                    sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
                            .invoke(buffer, new Object[0]);

                    cleaner.clean();

                } catch (Exception e) {

                    e.printStackTrace();

                }

                System.out.println("清空缓冲成功");

                return null;

            }

        });

    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    PdfToJpg.setup();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}
====================
package com.111.utils;


import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordToPDF1 {
    public static void wordToPDF(String docfile, String toFile,int type) {

        // 启动word
        ActiveXComponent app = new ActiveXComponent("Word.Application");
        try {
            app.setProperty("Visible", new Variant(false));
          //设置word程序非可视化运行
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Dispatch doc = Dispatch.invoke(
                    docs,
                    "Open",
                    Dispatch.Method,
                    new Object[] { docfile, new Variant(false),
                            new Variant(true) }, new int[1]).toDispatch();
            //new Variant(type),这里面的type的决定另存为什么类型的文件
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
                    toFile, new Variant(type) }, new int[1]);
            //作为PDF格式保存文件
            Variant f = new Variant(false);
            System.out.println(toFile+".pdf");
            //关闭文件
            Dispatch.call(doc, "Close", f);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //退出word程序
            app.invoke("Quit", new Variant[] {});
        }
    }

    public static void main(String[] args) {
        //源文件全路径
        //String docfile ="D:\\1.doc";
        String docfile ="D:\\房屋买卖合同范本(标准版).doc";
       // String docfile ="D:\\ceshi.doc";
        //for (int i = 0; i < 18; i++) {
            //些路径test为实际存在的目录,s后面为要另存为的文件名
            String toFile="d:\\"+1222;
            wordToPDF(docfile, toFile,17);
            //17 表示格式 为PDF
       // }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值