2020年4月10日 星期五

Maven create PDF file By WebGet Html content

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>

public static void createPdf(String url, String id, String outPath) throws Exception {
  //Pagesize, marginLeft, marginRight, marginTop, marginBottom
Document document = new Document(PageSize.A4, 20, 45, 20, 45);
PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream(outPath + id + ".pdf"));
document.open();
document.addAuthor("***");
document.addTitle("***");
document.addCreator("***");
document.addHeader("Domain", "www.***.gov.tw");
document.addKeywords("**");
document.addSubject("**");
                
                //Referenct by https://seed0111.blogspot.com/2020/04/maven-get-html-content-use-httppost.html
String _html = getHtmlContent(url, caseno);
try {
//InputStream cssInput =new URL("http://xxx/xx.css").openConnection().getInputStream();
InputStream cssInput = null;
//HTML To PDF
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document,new ByteArrayInputStream(_html.getBytes("UTF-8")),cssInput,Charset.forName("UTF-8"), new AsianFontProvider());
}catch (IOException e) {
                        log.error("createPdf has exception " + e.getMessage(), e);
               }finally {
                        document.close();
               }
}
※ 部份環境中文字會有亂碼產生,故_html.getBytes() =>  _html.getBytes("UTF-8") 排除

public class AsianFontProvider extends XMLWorkerFontProvider {
   @Override
    public Font getFont(final String fontname, final String encoding,
            final boolean embedded, final float size, final int style,
            final BaseColor color) {
            BaseFont bf = null;
        try {
        /*
        // 設定中文字體
String chMingliu0FontPath = "c:\\Windows\\Fonts\\mingliu.ttc,0";//windows內建的細明體                           
String chMingliu1FontPath = "c:\\Windows\\Fonts\\mingliu.ttc,1";//windows內建的新細明體                         
        */
        String chKaiuFontPath = "c:\\Windows\\Fonts\\KAIU.TTF";//windows內建的標楷體
bf = BaseFont.createFont(chKaiuFontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
           e.printStackTrace();
        }
        Font font = new Font(bf, size, style, color);
        font.setColor(color);
        return font;
    }

}
※ 部份環境無法讀取TTC 選TTF字型檔可以排除

// PDF設定縮放
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, document.getPageSize().getHeight(), 0.8f);
PdfAction action = PdfAction.gotoLocalPage(1, pdfDest, pdfWriter);
pdfWriter.setOpenAction(action);

Maven Get Html Content use HttpPost

//url: target url address
//id: post include params 
private static String getHtmlContent(String url, String id) throws IOException {
System.setProperty("javax.net.debug","ssl,handshake");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation","true");
String content = "";
try {   
                   //if use https or call https url addr than show handshake failed return, can add in pass check
SSLContext sslcontext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new 
              SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2"}, null, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        
        try {        
    //Use HttpGet method 
    //HttpGet webGet = new HttpGet(url);
                            //Use HttpPost method 
    HttpPost webGet = new HttpPost(url); 
    ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>( );
    params.add(new BasicNameValuePair("id" ,id )) ;
    webGet.setEntity(new UrlEncodedFormEntity(params));
    
    CloseableHttpResponse response = httpClient.execute(webGet);
    HttpEntity entity = response.getEntity();
    content = EntityUtils.toString(entity, "UTF-8");
    content = content.replace("&emsp;", "<font color='white'>_</font>");
    //System.out.println(content);
    EntityUtils.consume(entity);
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
} finally {
httpClient.close();
}         
} catch (Exception ex) {
log.error("createIgnoreVerifySSL has exception " + ex.getMessage(), ex);
}
    return content;
}