將jsp頁面轉化為圖片或pdf(一)(qq:1324981084)


java高級架構師全套vip教學視頻,需要的加我qq1324981084

在項目中遇見了將jsp頁面轉化為pdf的問題,試過itext,但是itext需要標准的html代碼,我的頁面中的一些屬性是itext所不識別的,所以努力了一段時間后就放棄了,后來發現htmlutil抓取網頁,將jsp頁面轉換成html,再將html轉化成pdf,問題很容易的解決了。我這里只上傳部分代碼:

jsp轉html:

這里用到的技術是抓取網頁htmlutil,將頁面中的內容抓取過來,形成html頁面,這里推薦這篇文章,還是比較好的

http://www.cnblogs.com/luotinghao/p/3800054.html

//filenameTemp 為定義的本地路徑文件            
File file = new File(filenameTemp); file.createNewFile(); write = new OutputStreamWriter(new FileOutputStream(filenameTemp), "UTF-8"); WebClient webClient = new WebClient(); webClient.getOptions().setJavaScriptEnabled(false);//設置javascript和css不可用 webClient.getOptions().setCssEnabled(false); //獲得你想要頁面的路徑(網址換成本項目想生成的頁面的請求路徑) HtmlPage page = webClient.getPage("http://localhost:8080/el/eldatamodification/selectsee.do?VERSION_ID=68aa2289f1801f249649f6729f554a59&COM_ID=b1805e8106cdb942fca62ed3798af371"); String str = page.asXml();
//html頭 write.write(
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"+str); write.close();

這樣我們就會將jsp轉化成html,但經過我的測試,jdk1.6好像不支持,或者是不是完全支持,我這里只能用jdk1.7

html轉pdf:

             NativeInterface.open();
             SwingUtilities.invokeLater(new Runnable() {
             public void run() {
             // SWT組件轉Swing組件,不初始化父窗體將無法啟動webBrowser
             JFrame frame = new JFrame("以DJ組件保存指定網頁截圖");
             // 加載google,最大保存為640x480的截圖
             frame.getContentPane().add(
             new
             Urlimage("http://localhost:8080/el/"+fileName+".html",  //這里是剛才html頁面的請求路徑
                     imgWidth, imgHeight,fileName,path),
             BorderLayout.CENTER);
             frame.setSize(800, 600);
             // 僅初始化,但不顯示
             frame.invalidate();
             frame.pack();
             frame.setVisible(false);
             }
             });
             NativeInterface.runEventPump();
public class Urlimage extends JPanel {
    /**
     * jsp轉jpg
     */
    private static final long serialVersionUID = 1L;

    // 行分隔符
    final static public String LS = System.getProperty("line.separator", "\n");

    // 文件分割符
    final static public String FS = System.getProperty("file.separator", "\\");

    // 以javascript腳本獲得網頁全屏后大小(建議事先保存網頁的寬高,由於執行速度的問題,有時獲得不到寬高)
    final static StringBuffer jsDimension;
    static {
        jsDimension = new StringBuffer();
        jsDimension.append("var width = 0;").append(LS);
        jsDimension.append("var height = 0;").append(LS);
        jsDimension.append("if(document.documentElement) {").append(LS);
        jsDimension.append("  width = Math.max(width, document.documentElement.scrollWidth);").append(LS);
        jsDimension.append("  height = Math.max(height, document.documentElement.scrollHeight);").append(LS);
        jsDimension.append("}").append(LS);
        jsDimension.append("if(self.innerWidth) {").append(LS);
        jsDimension.append("  width = Math.max(width, self.innerWidth);").append(LS);
        jsDimension.append("  height = Math.max(height, self.innerHeight);").append(LS);
        jsDimension.append("}").append(LS);
        jsDimension.append("if(document.body.scrollWidth) {").append(LS);
        jsDimension.append("  width = Math.max(width, document.body.scrollWidth);").append(LS);
        jsDimension.append("  height = Math.max(height, document.body.scrollHeight);").append(LS);
        jsDimension.append("}").append(LS);
        jsDimension.append("return width + ':' + height;");
    }
    public Urlimage(final String url, final int maxWidth, final int maxHeight,final String fileName,final String path) {
        super(new BorderLayout());
        JPanel webBrowserPanel = new JPanel(new BorderLayout());

        final JWebBrowser webBrowser = new JWebBrowser(null);
        webBrowser.setBarsVisible(false);
        webBrowser.navigate(url);
        webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
        add(webBrowserPanel, BorderLayout.CENTER);

        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4));

        webBrowser.addWebBrowserListener(new WebBrowserAdapter() {

            // 監聽加載進度
            public void loadingProgressChanged(WebBrowserEvent e) {
                // 當加載完畢時
                if (e.getWebBrowser().getLoadingProgress() == 100) {
//建議在這里寫一個死循環,一直執行直到獲得網頁的寬高位置,這里我就不寫程序了
// while(){}; String result
= (String) webBrowser.executeJavascriptWithResult(jsDimension.toString());//只想js代碼,獲得網頁的寬和高 int index = result == null ? -1 : result.indexOf(":"); NativeComponent nativeComponent = webBrowser.getNativeComponent(); Dimension originalSize = nativeComponent.getSize(); Dimension imageSize = new Dimension(Integer.parseInt(result.substring(0, index)), Integer.parseInt(result.substring(index + 1))); imageSize.width = Math.max(originalSize.width, imageSize.width + 50); imageSize.height = Math.max(originalSize.height, imageSize.height + 50); nativeComponent.setSize(imageSize); BufferedImage image = new BufferedImage(imageSize.width, imageSize.height, BufferedImage.TYPE_INT_RGB);//建立一個寬高顏色固定的圖片容器 nativeComponent.paintComponent(image);//繪制圖片,但有時候會數組越界,因為走的是線程和內部拋出異常,所以無法抓住 nativeComponent.setSize(originalSize); // 當網頁超出目標大小時 if (imageSize.width > maxWidth || imageSize.height > maxHeight) { // 截圖部分圖形 image = image.getSubimage(0, 0, maxWidth, maxHeight); /* * 此部分為使用縮略圖 int width = image.getWidth(), height = * image .getHeight(); AffineTransform tx = new * AffineTransform(); tx.scale((double) maxWidth / * width, (double) maxHeight / height); * AffineTransformOp op = new AffineTransformOp(tx, * AffineTransformOp.TYPE_NEAREST_NEIGHBOR); //縮小 image * = op.filter(image, null); */ } try { // 輸出圖像 // <!-- 需改動 --> final String fileNameLoc = "d:/huiyou21.jpg"; ImageIO.write(image, "jpg", new File(fileNameLoc));//改動這里變換格式 } catch (IOException ex) { ex.printStackTrace(); } } } } ); add(panel, BorderLayout.SOUTH); } }

這個方法我認為是很好的,執行速度一般在一秒到兩秒之間,但是在paintComponent的時候會形成全黑或者部分黑的pdf,雖然報錯但是無法抓住,本人建議是隨機獲得圖片中的一些點,來判斷時候黑色偏多,這樣就可以判斷出來,只是一些建議,希望這篇文章我能夠解決大家的問題,本人還會繼續完善這篇文章,本人菜鳥,請大家批評指點,謝謝。

jar包地址: 鏈接:http://pan.baidu.com/s/1boLkYWB 密碼:dhjx

鏈接:http://pan.baidu.com/s/1gf5dXHD 密碼:kod6

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM