posts - 5,  comments - 7,  trackbacks - 0
          項目要求,沒辦法,生成的jsp頁面要打印。
          于是要生成pdf大概查了一下itext主站的實例如下 :
            1/*
            2 * $Id: JFreeChartExample.java 1778 2005-06-02 11:05:39Z blowagie $
            3
           * $Name$
            4
           *
            5
           * This code is part of the 'iText Tutorial'.
            6
           * You can find the complete tutorial at the following address:
            7 * http://itextdocs.lowagie.com/tutorial/

            8 *
            9
           * This code is distributed in the hope that it will be useful,
           10
           * but WITHOUT ANY WARRANTY; without even the implied warranty of
           11
           * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
           12
           *
           13
           * itext-questions@lists.sourceforge.net
           14 */

           15package com.lowagie.examples.directcontent.graphics2D;
           16

           17import
           java.awt.Graphics2D;
           18import
           java.awt.geom.Rectangle2D;
           19import
           java.io.FileNotFoundException;
           20import
           java.io.FileOutputStream;
           21

           22import
           org.jfree.chart.ChartFactory;
           23import
           org.jfree.chart.JFreeChart;
           24import
           org.jfree.chart.plot.PlotOrientation;
           25import
           org.jfree.data.category.DefaultCategoryDataset;
           26import
           org.jfree.data.general.DefaultPieDataset;
           27import
           org.jfree.data.xy.XYSeries;
           28import
           org.jfree.data.xy.XYSeriesCollection;
           29

           30import
           com.lowagie.text.Document;
           31import
           com.lowagie.text.DocumentException;
           32import
           com.lowagie.text.Rectangle;
           33import
           com.lowagie.text.pdf.DefaultFontMapper;
           34import
           com.lowagie.text.pdf.PdfContentByte;
           35import
           com.lowagie.text.pdf.PdfTemplate;
           36import
           com.lowagie.text.pdf.PdfWriter;
           37

           38/** */
          /**
           39 * JFreeChart example.
           40 */

           41public class JFreeChartExample {
           42
              
           43    /** */
          /**
           44     * Creates some PDFs with JFreeCharts.
           45     * @param
           args no arguments needed
           46     */

           47    public static void main(String[] args) {
           48        System.out.println("JFreeChart example"
          );
           49        /** *//** the following line is a workaround for JDK 1.5 (fix by Adriaan Joubert) */

           50        org.jfree.text.TextUtilities.setUseDrawRotatedStringWorkaround(false);
           51        convertToPdf(getBarChart(), 400600"barchart.pdf"
          );
           52        convertToPdf(getPieChart(), 400600"piechart.pdf"
          );
           53        convertToPdf(getXYChart(), 400600"xychart.pdf"
          );
           54    }

           55    
           56    /** */
          /**
           57     * Converts a JFreeChart to PDF syntax.
           58     * @param
           filename    the name of the PDF file
           59     * @param
           chart        the JFreeChart
           60     * @param
           width        the width of the resulting PDF
           61     * @param
           height    the height of the resulting PDF
           62     */

           63    public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
           64        // step 1

           65        Document document = new Document(new Rectangle(width, height));
           66        try 
          {
           67            // step 2

           68            PdfWriter writer;
           69            writer = PdfWriter.getInstance(document, new
           FileOutputStream(filename));
           70            // step 3

           71            document.open();
           72            // step 4

           73            PdfContentByte cb = writer.getDirectContent();
           74            PdfTemplate tp =
           cb.createTemplate(width, height);
           75            Graphics2D g2d = tp.createGraphics(width, height, new
           DefaultFontMapper());
           76            Rectangle2D r2d = new Rectangle2D.Double(00
          , width, height);
           77
                      chart.draw(g2d, r2d);
           78
                      g2d.dispose();
           79            cb.addTemplate(tp, 00
          );
           80        }

           81        catch(DocumentException de) {
           82
                      de.printStackTrace();
           83        }

           84        catch (FileNotFoundException e) {
           85
                      e.printStackTrace();
           86        }

           87        // step 5
           88        document.close();
           89    }

           90    
           91    /** */
          /**
           92     * Gets an example barchart.
           93     * @return
           a barchart
           94     */

           95    public static JFreeChart getBarChart() {
           96        DefaultCategoryDataset dataset = new
           DefaultCategoryDataset();
           97        dataset.setValue(40"hits/hour""index.html"
          );
           98        dataset.setValue(20"hits/hour""download.html"
          );
           99        dataset.setValue(15"hits/hour""faq.html"
          );
          100        dataset.setValue(8"hits/hour""links.html"
          );
          101        dataset.setValue(31"hits/hour""docs.html"
          );
          102        return ChartFactory.createBarChart("Popularity of iText pages"
          ,
          103                "Page""hits/hour"
          , dataset,
          104                PlotOrientation.VERTICAL, falsetruefalse
          );
          105    }

          106    
          107    /** */
          /**
          108     * Gets an example piechart.
          109     * @return
           a piechart
          110     */

          111    public static JFreeChart getPieChart() {
          112        DefaultPieDataset dataset = new
           DefaultPieDataset();
          113        dataset.setValue("iText"60
          );
          114        dataset.setValue("cinema.lowagie.com"10
          );
          115        dataset.setValue("tutorial"30
          );
          116        return
           ChartFactory.createPieChart(
          117                "Website popularity"
          ,
          118
                          dataset,
          119                true
          ,
          120                true
          ,
          121                false
          );
          122    }

          123    
          124    /** */
          /**
          125     * Gets an example XY chart
          126     * @return
           an XY chart
          127     */

          128    public static JFreeChart getXYChart() {
          129        XYSeries series = new XYSeries("XYGraph"
          );
          130        series.add(15
          );
          131        series.add(27
          );
          132        series.add(33
          );
          133        series.add(45
          );
          134        series.add(54
          );
          135        series.add(65
          );
          136        XYSeriesCollection dataset = new
           XYSeriesCollection();
          137
                  dataset.addSeries(series);
          138        return
           ChartFactory.createXYLineChart(
          139                "XY Chart""X-axis""Y-axis"
          , dataset,
          140                PlotOrientation.VERTICAL, truetruefalse
          );
          141    }

          142}

          143

          不過這里遇到了一些問題。一個是日文顯示的問題。一個是分頁后圖片坐標的處理:
          生成Chart 之前的一個blog有記載。直接copy。生成了之后關鍵是如何把它加載在pdf文件里。
            1 Map tempmap = new HashMap();
            2        tempmap.put("_LocaleUtil"new
           LocaleUtil(Locale.JAPANESE));
            3        MessageUtil mu =

            4            new MessageUtil(
            5
                          tempmap,
            6                "jp.co.uss.cares100.message.bill.CaresRcdWeekPdf"
          );
            7        // pdfマージン 取得

            8        int marginleft = Integer.parseInt(mu.get("marginleft"));
            9        int marginright = Integer.parseInt(mu.get("marginright"
          ));
           10        int margintop = Integer.parseInt(mu.get("margintop"
          ));
           11        int marginbottom = Integer.parseInt(mu.get("marginbottom"
          ));
           12        String pageSize = mu.get("pageSize"
          );
           13

           14        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"
          );
           15        // 厳密な日付判定

           16        df.setLenient(false);
           17        String now = df.format(new
           Date());
           18        String fileName = PDF_FILE_PREFIX + now + ".pdf"
          ;
           19        DateFormat dateFormat =

           20            DateFormat.getDateTimeInstance(
           21
                          DateFormat.MEDIUM,
           22
                          DateFormat.MEDIUM,
           23
                          Locale.JAPAN);
           24
                  res.reset();
           25        res.setContentType("application/pdf"
          );
           26
                  res.setHeader(
           27            "Content-Disposition"
          ,
           28            "inline; filename="" + fileName + """
          );
           29        res.setHeader("Cache-Control"""
          );
           30        res.setHeader("Pragma"""
          );
           31        BufferedOutputStream bufOutStream =

           32            new BufferedOutputStream(res.getOutputStream());
           33
                  Document document;
           34        // ページサイズを設定する

           35        if (pageSize.equalsIgnoreCase("A4")) {
           36            document =

           37                new Document(
           38
                              PageSize.A4,
           39
                              marginleft,
           40
                              marginright,
           41
                              margintop,
           42
                              marginbottom);
           43            // ページサイズを設定する            

           44        }
           else {
           45            document =

           46                new Document(
           47
                              PageSize.A3,
           48
                              marginleft,
           49
                              marginright,
           50
                              margintop,
           51
                              marginbottom);
           52        }

           53        PdfWriter pdfwriter = PdfWriter.getInstance(document, bufOutStream);
           54        // ドキュメントオープン 

           55        document.open();
           56        //加載一個封面

           57        document.add(CaresRecordDayPdfProcess.getFaceTable(req,document,(List)map.get("baseInfoList")));
           58
                  document.newPage();
           59        //加載頭信息

           60        document.add(
           61
                      getHeadTable(
           62                map.get("userName"
          ).toString(),
           63                map.get("baseInfo"
          ).toString(),
           64                map.get("dateInfo"
          ).toString()));
           65        document.add(getPhrase("● 介護記録"
          ));
           66        //加載數據table

           67        document.add(
           68
                      getDataTable(
           69                (List) map.get("title1List"
          ),
           70                (List) map.get("data1List"
          )));
           71        //compute the height of the chart

           72        int height = 405, dataCount = 0;//調節chart圖片的顯示Y坐標
           73        dataCount = ((List) map.get("data1List")).size();
           74        height = height - dataCount * 20;//table的row高度,每加一row那么圖片坐標就要低20

           75        while(true){//分頁后應該顯示的Y坐標,A4紙的高度是800
           76            if(height < 0){
           77                height += 40*20
          ;
           78            }
          else{
           79                if(height > 500)
          {
           80
                              document.newPage();
           81                    height = 510
          ;
           82                }

           83                height -= 10;
           84                break
          ;
           85            }

           86        }

           87        document.add(getPhrase("● バイタル"));
           88        PdfContentByte cb =
           pdfwriter.getDirectContent();
           89        PdfTemplate tp = cb.createTemplate(500300
          );
           90        //這里很重要,解決了東方語言顯示的問題。

           91        Graphics2D g2d =
           92            tp.createGraphics(
           93                500
          ,
           94                300
          ,
           95                new
           AsianFontMapper(
           96
                              AsianFontMapper.JapaneseFont_Min,
           97
                              AsianFontMapper.JapaneseEncoding_H));
           98        Rectangle2D r2d = new Rectangle2D.Double(00500300
          );
           99        JFreeChart chart =
           getChart(map);
          100
                  chart.draw(g2d, r2d);
          101
                  g2d.dispose();
          102        cb.addTemplate(tp, 48
          , height);
          103        // ドキュメントクローズ

          104        document.close();
          105
                  bufOutStream.flush();
          106        bufOutStream.close();

          關鍵是以下幾段代碼:
          a)生成pdf
           1 public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
           2        // step 1

           3        Document document = new Document(new Rectangle(width, height));
           4        try 
          {
           5            // step 2

           6            PdfWriter writer;
           7            writer = PdfWriter.getInstance(document, new
           FileOutputStream(filename));
           8            // step 3

           9            document.open();
          10            // step 4

          11            PdfContentByte cb = writer.getDirectContent();
          12            PdfTemplate tp =
           cb.createTemplate(width, height);
          13            Graphics2D g2d = tp.createGraphics(width, height, new
           DefaultFontMapper());
          14            Rectangle2D r2d = new Rectangle2D.Double(00
          , width, height);
          15
                      chart.draw(g2d, r2d);
          16
                      g2d.dispose();
          17            cb.addTemplate(tp, 00
          );
          18        }

          19        catch(DocumentException de) {
          20
                      de.printStackTrace();
          21        }

          22        catch (FileNotFoundException e) {
          23
                      e.printStackTrace();
          24        }

          25        // step 5
          26        document.close();
          27    }
          b)漢語,日語和其他東方語言的支持:
           1PdfContentByte cb = pdfwriter.getDirectContent();
           2        PdfTemplate tp = cb.createTemplate(500300
          );
           3        Graphics2D g2d =//關鍵部分

           4            tp.createGraphics(
           5                500
          ,
           6                300
          ,
           7                new
           AsianFontMapper(
           8
                              AsianFontMapper.JapaneseFont_Min,
           9
                              AsianFontMapper.JapaneseEncoding_H));
          10        Rectangle2D r2d = new Rectangle2D.Double(00500300
          );
          11        JFreeChart chart =
           getChart(map);
          12
                  chart.draw(g2d, r2d);
          13
                  g2d.dispose();
          14        cb.addTemplate(tp, 48, height);
          需要加載的包是iTextAsian.jar
          下載地址:
          http://sourceforge.net/project/downloading.php?groupname=itextpdf&filename=iTextAsian.jar&use_mirror=nchc
          posted on 2008-11-25 10:26 Vincent-chen 閱讀(1150) 評論(0)  編輯  收藏 所屬分類: JfreeChart

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 蒙阴县| 大新县| 盖州市| 屯门区| 裕民县| 叙永县| 洞口县| 临泉县| 马龙县| 象山县| 监利县| 河西区| 东山县| 华安县| 宜都市| 长阳| 夏津县| 吉水县| 长岛县| 固始县| 昌黎县| 呼和浩特市| 马山县| 泗洪县| 长泰县| 都兰县| 岗巴县| 吉安县| 行唐县| 叙永县| 陵川县| 平江县| 瓦房店市| 兴海县| 老河口市| 类乌齐县| 罗城| 长兴县| 金华市| 桐乡市| 宾阳县|