JAVA+代码+--++JSP+-+HTML+-++PDF+转化

 

package test.byd.com.dcc.unittest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.catalina.ssi.ByteArrayServletOutputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.methods.GetMethod;
import org.xhtmlrenderer.context.StyleReference;
import org.xhtmlrenderer.extend.UserAgentCallback;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import org.xml.sax.SAXException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.HtmlWriter;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.sun.xml.internal.ws.util.ByteArrayBuffer;


public class TestPdf {
 public static void main(String []args) throws Exception{
  
//    createPDFSucess();
    
//  System.out.println("ok");
  
      createPDFMethod();
       
 }
 
 private static void createPDFMethod() throws HttpException, IOException, DocumentException{
  
  long time=System.currentTimeMillis();
  
  URL url=new URL("http://localhost:8080/DCC/version/getpdf");
  HttpClient client=new HttpClient();
  HttpHost host=new HttpHost("localhost");
  client.getHostConfiguration().setHost(host);
  GetMethod method=new GetMethod(url.toString());
  client.executeMethod(method);
  //获取响应的html 文本
  String contents=method.getResponseBodyAsString();
  System.out.println(contents);
  contents=contents.replace(" ", "   ");
  contents=contents.replace("/DCC/", "");
  int index=contents.lastIndexOf("<head>");
  int index2=contents.lastIndexOf("<title>");
  
  contents=contents.substring(0,index)+"<head>"+contents.substring(index2);
//  System.out.println(contents);
  
  System.out.println("-------------------------------------------");
  
  String inputfile="WebContent/views/test/pdf/testHttpClient.html";
 
  writeHTML(contents,inputfile);
  
  String outputFile = "D:/firstdoc1012.pdf";
  createPDF(inputfile, outputFile);
  
  //获得生成的PDF文件的总页码
  PdfReader pdfreader=new PdfReader(outputFile);
        int pageCount=pdfreader.getNumberOfPages();
        System.out.println(pageCount);
        System.out.println("-------------------------------------------");
        contents=readerHTML(inputfile);
        int number=contents.indexOf("<td width=\"15%\" class=\"st_5\">1/</td>");
        String str="<td width=\"15%\" class=\"st_5\">1/";
        contents= contents.substring(0,number)+str+pageCount+contents.substring(number+str.length());
        writeHTML(contents,inputfile);
       
        createPDF(inputfile,outputFile);
      
        System.out.println(System.currentTimeMillis()-time);
       
       
 
 }
 
 
 /**
  * @param inputFile
  * @param outputFile
  * @throws DocumentException
  * @throws IOException
  * HTML转PDF方法
  */
 private static void createPDF(String inputFile,String outputFile) throws DocumentException, IOException{
  String url2 = new File(inputFile).toURI().toURL().toString();
  OutputStream os =new FileOutputStream(outputFile);
  ITextRenderer renderer = new ITextRenderer();
  renderer.setDocument(url2);
  //中文转码问题
  ITextFontResolver fontResolver = renderer.getFontResolver();
  fontResolver.addFont("C:/Windows/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

  renderer.layout();
  renderer.createPDF(os);
  System.out.println("转换成功");
  os.close();
 }
 
 /**
  * 写文件
  * @param contents   文件字符串内容
  * @param path       写入的文件地址
  * @throws MalformedURLException
  */
 private static void writeHTML(String contents,String path) {
  try  {
    path=new File(path).toURI().toURL().toString();
         FileOutputStream fos  =   new  FileOutputStream(path.substring(path.indexOf("/")));
         OutputStreamWriter osw  =   new  OutputStreamWriter(fos,  "UTF-8" );
         osw.write(contents);
         osw.flush();
      }  catch  (Exception e) {
         e.printStackTrace();
     }
 }
 
 private static String readerHTML(String path){
  StringBuffer contents=new StringBuffer();
   try  {
     path=new File(path).toURI().toURL().toString();
            FileInputStream fis  =   new  FileInputStream(path.substring(path.indexOf("/")));
            InputStreamReader isr  =   new  InputStreamReader(fis,  "UTF-8" );
            BufferedReader br  =   new  BufferedReader(isr);
            String line  =   null ;
             while  ((line  =  br.readLine())  !=   null ) {
              contents.append(line);
              contents.append("\r\n ");  //  补上换行符
            }
        }  catch  (Exception e) {
            e.printStackTrace();
        }
        return contents.toString();
 }
}
 
 

阅读更多
个人分类: java
下一篇更新版本的 转化PDF
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭