html 網頁生成pdf 文件

網頁:javascript

注意網頁標籤必須關閉,不能夠單個標籤css

<html xmlns="http://www.w3.org/1999/html">
<head>
    <title>Title</title>
</head>
<body style="height: 825px; width: 1100px">
    <div style="height: 225px"></div>
    <div style="text-align: center;font-size: 43px;">${workOrder.shopNameEn}</div>
    <div  style="text-align: center;font-size: 43px; text-decoration: underline;">E&M Maintenance Report</div>
    <div style="height: 211px"></div>
    <div style="margin-left: 115px">
        <div style="font-size: 24px;">By  GZ XXX M&E Engineering Co .Ltd</div>
        <div style="font-size: 24px;">${reportDateStr}</div>
    </div>
</body>
</html>

網頁controllerhtml

/**
     *  網頁報表首頁
     */
    @RequestMapping(value = "/first_page/{workOrderId}")
    public String firstPage(@PathVariable Integer workOrderId , Model model){
        WorkOrder workOrder = workOrderService.selectById(workOrderId);
        model.addAttribute("workOrder",workOrder);
        SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy", Locale.ENGLISH);
        String reportDateStr = sdf.format(workOrder.getAppointTimeStart());//使用預定日期
        model.addAttribute("reportDateStr",reportDateStr);
        return PREFIX + "workOrder_firstPage.html";
    }

網頁鏈接必須當成外接api開放前端

前端pdf生成按鈕java

<#button name="pdf預覽" icon="fa-file-pdf-o" clickFun="WorkOrderDetail.printReceipt()" />

js:web

利用pdfjs 產生pdf預覽界面api

WorkOrderDetail.printReceipt = function () {
    var workOrderId = $("#workOrderId").text();
    window.open('/static/js/plugins/pdfjs/web/viewer.html?file=' + encodeURIComponent(Feng.ctxPath + "/workOrder/print_receipt/"+ workOrderId,"pdf"));

};

controller:app

/**
     *  完工記錄pdf
     */
    @Permission
    @RequestMapping(value = "/print_receipt/{workOrderId}")
    @ResponseBody
    public void printReceipt(@PathVariable Integer workOrderId){
        workOrderService.printReceipt(workOrderId);
    }

pom.xml : 須要引入的包測試

<!--pdf 導出須要的jar包 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.6</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.6</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.1</version>
        </dependency>

 

serviceImpl 接口就省略不放上來this

1: 代碼沒有寫完,感受效果不是太理想就放棄了

2: 能夠把獲取打印網頁html,保存本地html 文件,再重啓讀取html文件,生成pdf 文件後,再刪除html文件的的過程, 改爲直接append 拼接html的string而後直接生成pdf文件

3: 後續能夠利用document 的 add page 增長頁面,

/**
     *  完工記錄pdf入口,
     */
    public boolean printReceipt(Integer workOrderId){
        //html預覽title
        WorkOrder workOrder = this.selectById(workOrderId);
        String title = workOrder.getShopNameCh() + "-完工記錄.pdf";
        int port = serverProperties.getPort();
        //首頁生成pdf文件
        try {
            URL url = new URL("http://localhost:" + port + "/workOrder/first_page/" + workOrderId);
            File file  = createPdfByUrl(url);
            showReceiptOrder(file , title);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 利用網頁url 建立單個pdf文件
     * @param url
     * @return
     */
    private File createPdfByUrl(URL url){
        //pdf 路徑
        String fileName = String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".pdf";
        String picSavePath = gunsProperties.getFileUploadPath();
        String subFile = "workOrderPdf"+ "/";
        String realPath = ServerUtils.createShopPictureUploadPath(picSavePath+subFile) + fileName;
        File file = new File(realPath);

        //html路徑
        String htmlFileName = String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".HTML";
        String htmlPath = ServerUtils.createShopPictureUploadPath(picSavePath+subFile) + htmlFileName;


        PdfWriter writer = null;
        try {
            //第一步,建立一個 iTextSharp.text.Document對象的實例:
            Rectangle pageSize = new Rectangle(720, 540); //這隻頁面大小
            Document document = new Document(pageSize);
            // 測試頁面大小
//            PdfReader reader = new PdfReader(picSavePath + subFile + "xxxx店-完工記錄-.pdf");
//            Document document2 = new Document(reader.getPageSize(1));
//            reader.close();
//            document2.close();
            //第二步,爲該Document建立一個Writer實例:
            FileOutputStream fos = new FileOutputStream(realPath);
            writer = PdfWriter.getInstance(document, fos);
            //第三步,打開當前Document
            document.open();
            //第四步,爲當前Document添加內容:
            //document.add(new Paragraph("Hello World"));
            if(convertUrlToHtml(url , htmlPath) == false){
                throw new GunsException(BizExceptionEnum.CREATE_HTML_FILE_ERROR);
            }
            FileInputStream fis = new FileInputStream(htmlPath);
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, fis);
            //第五步,關閉Document
            document.close();
            fis.close();
            fos.close();
            new File(htmlPath).delete(); // 刪除html文件
            if(ToolUtil.isEmpty(file)){
                throw new GunsException(BizExceptionEnum.CREATE_PDF_ERROR);
            }
            return file;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            writer.close();
        }

    }

    /**
     * 把url 上的html 保存爲本地html文件
     * @param url
     * @param htmlPath
     * @return
     */
    public boolean convertUrlToHtml(URL url , String htmlPath){
        try {
            File htmlFile = new File(htmlPath);
            InputStream is;//接收字節輸入流
            FileOutputStream fos = new FileOutputStream(htmlFile);//字節輸出流
            is = url.openStream();
            BufferedInputStream bis = new BufferedInputStream(is);//爲字節輸入流加緩衝
            BufferedOutputStream bos = new BufferedOutputStream(fos);//爲字節輸出流加緩衝
            int length;
            byte[] bytes = new byte[1024*20];
            while((length = bis.read(bytes, 0, bytes.length)) != -1){
                fos.write(bytes, 0, length);
            }
            bos.close();
            fos.close();
            bis.close();
            is.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * pdf文件前端展現
     * @param file
     * @param httpTitleName
     */
    private void showReceiptOrder(File file ,String httpTitleName){ // httpTitleName = "xx店-完工記錄.pdf"
        try{
            FileInputStream fileInputStream = new FileInputStream(file);
            HttpServletResponse response = HttpKit.getResponse();
            response.setHeader(
                    "Content-Disposition",
                    "attachment;fileName="
                            + new String( httpTitleName.getBytes("utf-8"),"ISO8859-1")
            );
            response.setContentType( "multipart/form-data");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        }catch (IOException e){
            e.printStackTrace();
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("成功顯示文件!");
        }
    }

效果以下:

html 文件

看上去效果還能夠,

可是生成的pdf文件

其實這個還要考慮中文直接,導入simsun 宋體包,還有考慮把圖片改爲base64格式才能夠讀取, 因爲對應的html文件,沒法讀取js,以及大部分的css效果,若是對報表要求比較嚴格,內容比較多,樣式調整就很是麻煩

相關文章
相關標籤/搜索