Java 类com.lowagie.text.pdf.DefaultFontMapper 实例源码

项目:rapidminer    文件:ImageExporter.java   
private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException {
    Component component = printableComponent.getExportComponent();
    int width = component.getWidth();
    int height = component.getHeight();
    try (FileOutputStream fs = new FileOutputStream(outputFile)) {
        switch (formatName) {
            case PDF:
                // create pdf document with slightly increased width and height
                // (otherwise the image gets cut off)
                Document document = new Document(new Rectangle(width + 5, height + 5));
                PdfWriter writer = PdfWriter.getInstance(document, fs);
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                component.print(g2);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
                document.close();
                break;
            case SVG:
                exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height)));
                break;
            case EPS:
                exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height)));
                break;
            default:
                // cannot happen
                break;
        }
    } catch (Exception e) {
        throw new ImageExportException(I18N.getMessage(I18N.getUserErrorMessagesBundle(),
                "error.image_export.export_failed"), e);
    }
}
项目:balloonist    文件:PdfFriend.java   
public static int registerMacOSXFontDirectories(DefaultFontMapper designatedFontMapper)
{
    int count = 0;

    count += insertDirectory("/System/Library/Fonts/", designatedFontMapper);
    count += insertDirectory("/Library/Fonts/", designatedFontMapper);

    String userFontDir = System.getProperty("user.home")+"/Library/Fonts/";
    Logger.println("Checking user font dir: "+userFontDir);
    count += insertDirectory(userFontDir, designatedFontMapper);

    Logger.print("Registered ");
    Logger.print(count);
    Logger.println(" Mac OS X font(s).");

    return count;
}
项目:balloonist    文件:PdfFriend.java   
/**
 * @return the number of settings that were changed.
 */
public static int setEmbedding(boolean designatedEmbedding, DefaultFontMapper defaultFontMapper)
{
    int changed = 0;

    Iterator walk = defaultFontMapper.getMapper().values().iterator();

    while (walk.hasNext())
    {
        DefaultFontMapper.BaseFontParameters params = (DefaultFontMapper.BaseFontParameters) walk.next();

        if (params.embedded!=designatedEmbedding)
        {
            params.embedded=designatedEmbedding;
            changed++;
        }
    }

    return changed;
}
项目:balloonist    文件:PdfFriend.java   
private static int insertDirectory(String requestedDirectory,
        DefaultFontMapper defaultFontMapper)
{
    int ffCount = FontFactory.registerDirectory(requestedDirectory);

    int fmCount = 0;

    if (defaultFontMapper!=null)
    {
        fmCount = defaultFontMapper.insertDirectory(requestedDirectory);
    }

    if (ffCount>fmCount)
        return ffCount;
    else
        return fmCount;
}
项目:geomajas-project-server    文件:PdfContext.java   
/**
 * Draw text in the center of the specified box.
 *
 * @param text text
 * @param font font
 * @param box box to put text int
 * @param fontColor colour
 */
public void drawText(String text, Font font, Rectangle box, Color fontColor) {
    template.saveState();
    // get the font
    DefaultFontMapper mapper = new DefaultFontMapper();
    BaseFont bf = mapper.awtToPdf(font);
    template.setFontAndSize(bf, font.getSize());

    // calculate descent
    float descent = 0;
    if (text != null) {
        descent = bf.getDescentPoint(text, font.getSize());
    }

    // calculate the fitting size
    Rectangle fit = getTextSize(text, font);

    // draw text if necessary
    template.setColorFill(fontColor);
    template.beginText();
    template.showTextAligned(PdfContentByte.ALIGN_LEFT, text, origX + box.getLeft() + 0.5f
            * (box.getWidth() - fit.getWidth()), origY + box.getBottom() + 0.5f
            * (box.getHeight() - fit.getHeight()) - descent, 0);
    template.endText();
    template.restoreState();
}
项目:itext2    文件:JFreeChartTest.java   
/**
  * Converts a JFreeChart to PDF syntax.
  * @param filename the name of the PDF file
  * @param chart        the JFreeChart
  * @param width        the width of the resulting PDF
  * @param height   the height of the resulting PDF
  */
 public static void convertToPdf(JFreeChart chart, int width, int height, String filename) {
    // step 1
    Document document = new Document(new Rectangle(width, height));
    try {
        // step 2
        PdfWriter writer;
writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream(filename));
// step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        Graphics2D g2d = tp.createGraphics(width, height, new DefaultFontMapper());
        Rectangle2D r2d = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2d, r2d);
        g2d.dispose();
        tp.sanityCheck();
        cb.addTemplate(tp, 0, 0);
        cb.sanityCheck();
    }
    catch(DocumentException de) {
        de.printStackTrace();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // step 5
    document.close();
 }
项目:balloonist    文件:PdfFriend.java   
public static int registerFontDirectories(DefaultFontMapper designatedFontMapper)
{
    int count = 0;

    final long START = System.currentTimeMillis();

    if (PlatformFriend.RUNNING_ON_WINDOWS)
    {
        count += registerWindowsFontDirectories(designatedFontMapper);
    }
    else if (PlatformFriend.RUNNING_ON_MAC)
    {
        count += registerMacOSXFontDirectories(designatedFontMapper);
    }
    else
    {
        count += insertDirectory("/usr/X/lib/X11/fonts/TrueType", designatedFontMapper);
        count += insertDirectory("/usr/openwin/lib/X11/fonts/TrueType", designatedFontMapper);
        count += insertDirectory("/usr/share/fonts/default/TrueType", designatedFontMapper);
        count += insertDirectory("/usr/X11R6/lib/X11/fonts/ttf", designatedFontMapper);
    }

    final long DURATION = (System.currentTimeMillis() - START);

    Logger.println("registerFontDirectories took: "+((double)DURATION/1000.0)+ " sec(s)");

    return count;
}
项目:balloonist    文件:PdfFriend.java   
public static int registerWindowsFontDirectories(DefaultFontMapper designatedFontMapper)
{
    int count = 0;

    count += insertDirectory("c:/windows/fonts", designatedFontMapper);
    count += insertDirectory("c:/winnt/fonts", designatedFontMapper);
    count += insertDirectory("d:/windows/fonts", designatedFontMapper);
    count += insertDirectory("d:/winnt/fonts", designatedFontMapper);

    return count;
}
项目:balloonist    文件:PdfFriend.java   
public static void writeToPortableDocumentFormat(Drawing drawing, OutputStream outputStream, float drawingWidth, float drawingHeight, float pageWidth, float pageHeight) throws DocumentException
{
    com.lowagie.text.Document document = new com.lowagie.text.Document();

    document.setPageSize(new com.lowagie.text.Rectangle(pageWidth, pageHeight));

    PdfWriter writer = PdfWriter.getInstance(document, outputStream);

    document.open();

    PdfContentByte cb = writer.getDirectContent();

    PdfTemplate tp = cb.createTemplate(drawingWidth, drawingHeight);

    DefaultFontMapper mapper = PdfFriend.getFontMapper();
    final DefaultDrawingContext drawingContext = (DefaultDrawingContext) DrawingContextFactory.getDrawingContext();
    Graphics2D g2 = null;

    if (BalloonEngineState.getInstance().isPreserveAccuracy())
        g2 = tp.createGraphicsShapes(drawingWidth, drawingHeight);
    else
        g2 = tp.createGraphics(drawingWidth, drawingHeight, mapper);

    drawingContext.setGraphics(g2);
    drawingContext.setTargetingPdf(true);
    drawingContext.setSelected(new Selection());
    drawingContext.setExportProfile(new SimpleExportProfile());

    drawing.drawOnto(drawingContext);

    Dimension dimension = new Dimension((int)drawingWidth, (int)drawingHeight);

    g2.dispose();
    cb.addTemplate(tp, 0, 0);
    document.close();
}
项目:rapidminer-studio    文件:ImageExporter.java   
private void exportVectorGraphics(String formatName, File outputFile) throws ImageExportException {
    Component component = printableComponent.getExportComponent();
    int width = component.getWidth();
    int height = component.getHeight();
    try (FileOutputStream fs = new FileOutputStream(outputFile)) {
        switch (formatName) {
            case PDF:
                // create pdf document with slightly increased width and height
                // (otherwise the image gets cut off)
                Document document = new Document(new Rectangle(width + 5, height + 5));
                PdfWriter writer = PdfWriter.getInstance(document, fs);
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                component.print(g2);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
                document.close();
                break;
            case SVG:
                exportFreeHep(component, fs, new SVGGraphics2D(fs, new Dimension(width, height)));
                break;
            case EPS:
                exportFreeHep(component, fs, new PSGraphics2D(fs, new Dimension(width, height)));
                break;
            default:
                // cannot happen
                break;
        }
    } catch (Exception e) {
        throw new ImageExportException(I18N.getMessage(I18N.getUserErrorMessagesBundle(),
                "error.image_export.export_failed"), e);
    }
}
项目:beast-mcmc    文件:MapperFrameOld.java   
public final void doExportPDF() {
        FileDialog dialog = new FileDialog(this,
                "Export PDF Image...",
                FileDialog.SAVE);

        dialog.setVisible(true);
        if (dialog.getFile() != null) {
            File file = new File(dialog.getDirectory(), dialog.getFile());

            Rectangle2D bounds = mapperPanel.getExportableComponent().getBounds();
            Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
            try {
                // step 2
                PdfWriter writer;
                writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
                document.open();
// step 4
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
                Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper());
                mapperPanel.getExportableComponent().print(g2d);
                g2d.dispose();
                cb.addTemplate(tp, 0, 0);
            }
            catch (DocumentException de) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            document.close();
        }
    }
项目:magate    文件:PDFGenerator.java   
/**
 * Plot PDF chart
 * 
 * @param chart
 * @param fileName
 * @param width
 * @param height
 */
public static void generatePDFChart(JFreeChart chart, String fileName, int width, int height) {

    // write the chart to a PDF file... 

       File outputPlotResult = new File(new File(MaGateProfile.chartLocation()), fileName + "-" + UUID.randomUUID().toString() + ".pdf");

       try {
        saveChartAsPDF(outputPlotResult, chart, width, height, new DefaultFontMapper());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
}
项目:geomajas-project-server    文件:PdfContext.java   
/**
 * Return the text box for the specified text and font.
 *
 * @param text text
 * @param font font
 * @return text box
 */
public Rectangle getTextSize(String text, Font font) {
    template.saveState();
    // get the font
    DefaultFontMapper mapper = new DefaultFontMapper();
    BaseFont bf = mapper.awtToPdf(font);
    template.setFontAndSize(bf, font.getSize());
    // calculate text width and height
    float textWidth = template.getEffectiveStringWidth(text, false);
    float ascent = bf.getAscentPoint(text, font.getSize());
    float descent = bf.getDescentPoint(text, font.getSize());
    float textHeight = ascent - descent;
    template.restoreState();
    return new Rectangle(0, 0, textWidth, textHeight);
}
项目:ieo-beast    文件:TracerFrame.java   
public final void doExportPDF() {
        FileDialog dialog = new FileDialog(this,
                "Export PDF Image...",
                FileDialog.SAVE);

        dialog.setVisible(true);
        if (dialog.getFile() != null) {
            File file = new File(dialog.getDirectory(), dialog.getFile());

            Rectangle2D bounds = tracePanel.getExportableComponent().getBounds();
            Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
            try {
                // step 2
                PdfWriter writer;
                writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
                document.open();
// step 4
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
                Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper());
                tracePanel.getExportableComponent().print(g2d);
                g2d.dispose();
                cb.addTemplate(tp, 0, 0);
            }
            catch (DocumentException de) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            document.close();
        }
    }
项目:ieo-beast    文件:TemporalAnalysisFrame.java   
public final void doExportPDF() {
    FileDialog dialog = new FileDialog(this,
            "Export PDF Image...",
            FileDialog.SAVE);

    dialog.setVisible(true);
    if (dialog.getFile() != null) {
        File file = new File(dialog.getDirectory(), dialog.getFile());

        Rectangle2D bounds = temporalAnalysisPlotPanel.getExportableComponent().getBounds();
        Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
        try {
            // step 2
            PdfWriter writer;
            writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            // step 3
            document.open();
            // step 4
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
            Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper());
            temporalAnalysisPlotPanel.getExportableComponent().print(g2d);
            g2d.dispose();
            cb.addTemplate(tp, 0, 0);
        }
        catch (DocumentException de) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
                    "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e,
                    "Export PDF Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        document.close();
    }
}
项目:ieo-beast    文件:MapperFrame.java   
public final void doExportPDF() {
        FileDialog dialog = new FileDialog(this,
                "Export PDF Image...",
                FileDialog.SAVE);

        dialog.setVisible(true);
        if (dialog.getFile() != null) {
            File file = new File(dialog.getDirectory(), dialog.getFile());

            Rectangle2D bounds = mapperPanel.getExportableComponent().getBounds();
            Document document = new Document(new com.lowagie.text.Rectangle((float) bounds.getWidth(), (float) bounds.getHeight()));
            try {
                // step 2
                PdfWriter writer;
                writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
                document.open();
// step 4
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate((float) bounds.getWidth(), (float) bounds.getHeight());
                Graphics2D g2d = tp.createGraphics((float) bounds.getWidth(), (float) bounds.getHeight(), new DefaultFontMapper());
                mapperPanel.getExportableComponent().print(g2d);
                g2d.dispose();
                cb.addTemplate(tp, 0, 0);
            }
            catch (DocumentException de) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e,
                        "Export PDF Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            document.close();
        }
    }
项目:scratch-bench    文件:MainMenu.java   
public void paintToPDF(JEditorPane jep,File file) {
  try {
    jep.setBounds(0, 0, (int) convertToPixels(612 - 58), (int) convertToPixels(792 - 60));

    Document document = new Document();
    FileOutputStream fos = new FileOutputStream(file);
    PdfWriter writer = PdfWriter.getInstance(document, fos);

    document.setPageSize(new com.lowagie.text.Rectangle(612, 792));
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    cb.saveState();
    cb.concatCTM(1, 0, 0, 1, 0, 0);

    DefaultFontMapper mapper = new DefaultFontMapper();
    mapper.insertDirectory("c:/windows/fonts");

    Graphics2D g2 = cb.createGraphics(612, 792, mapper, true, .95f);

    AffineTransform at = new AffineTransform();
    at.translate(convertToPixels(20), convertToPixels(20));
    at.scale(pixelToPoint, pixelToPoint);

    g2.transform(at);

    g2.setColor(Color.WHITE);
    g2.fill(jep.getBounds());

    Rectangle alloc = getVisibleEditorRect(jep);
    jep.getUI().getRootView(jep).paint(g2, alloc);

    g2.setColor(Color.BLACK);
    g2.draw(jep.getBounds());

    g2.dispose();
    cb.restoreState();
    document.close();
    fos.flush();
    fos.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
}
项目:gcs    文件:CharacterSheet.java   
/**
 * @param file The file to save to.
 * @return <code>true</code> on success.
 */
public boolean saveAsPDF(File file) {
    HashSet<Row> changed = expandAllContainers();
    try {
        PrintManager settings = mCharacter.getPageSettings();
        PageFormat format = settings != null ? settings.createPageFormat() : createDefaultPageFormat();
        Paper paper = format.getPaper();
        float width = (float) paper.getWidth();
        float height = (float) paper.getHeight();

        adjustToPageSetupChanges(true);
        setPrinting(true);

        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(new com.lowagie.text.Rectangle(width, height));
        try (FileOutputStream out = new FileOutputStream(file)) {
            PdfWriter writer = PdfWriter.getInstance(pdfDoc, out);
            int pageNum = 0;
            PdfContentByte cb;

            pdfDoc.open();
            cb = writer.getDirectContent();
            while (true) {
                PdfTemplate template = cb.createTemplate(width, height);
                Graphics2D g2d = template.createGraphics(width, height, new DefaultFontMapper());

                if (print(g2d, format, pageNum) == NO_SUCH_PAGE) {
                    g2d.dispose();
                    break;
                }
                if (pageNum != 0) {
                    pdfDoc.newPage();
                }
                g2d.setClip(0, 0, (int) width, (int) height);
                print(g2d, format, pageNum++);
                g2d.dispose();
                cb.addTemplate(template, 0, 0);
            }
            pdfDoc.close();
        }
        return true;
    } catch (Exception exception) {
        return false;
    } finally {
        setPrinting(false);
        closeContainers(changed);
    }
}
项目:Keel3.0    文件:VisualizePanelCharts2D.java   
private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412,
                        new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}
项目:KEEL    文件:VisualizePanelCharts2D.java   
private void topdfjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_topdfjButtonActionPerformed
    // Save chart as a PDF file
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Save chart");
    KeelFileFilter fileFilter = new KeelFileFilter();
    fileFilter.addExtension("pdf");
    fileFilter.setFilterName("PDF images (.pdf)");
    chooser.setFileFilter(fileFilter);
    chooser.setCurrentDirectory(Path.getFilePath());
    int opcion = chooser.showSaveDialog(this);
    Path.setFilePath(chooser.getCurrentDirectory());
    if (opcion == JFileChooser.APPROVE_OPTION) {
        String nombre = chooser.getSelectedFile().getAbsolutePath();
        if (!nombre.toLowerCase().endsWith(".pdf")) {
            // Add correct extension
            nombre += ".pdf";
        }
        File tmp = new File(nombre);
        if (!tmp.exists() || JOptionPane.showConfirmDialog(this, "File " + nombre + " already exists. Do you want to replace it?",
                "Confirm", JOptionPane.YES_NO_OPTION, 3) == JOptionPane.YES_OPTION) {
            try {
                Document document = new Document();
                PdfWriter writer = PdfWriter.getInstance(document,
                        new FileOutputStream(nombre));
                document.addAuthor("KEEL");
                document.addSubject("Attribute comparison");
                document.open();
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(550, 412);
                Graphics2D g2 = tp.createGraphics(550, 412,
                        new DefaultFontMapper());
                Rectangle2D r2D = new Rectangle2D.Double(0, 0, 550, 412);
                chart2.setBackgroundPaint(Color.white);
                chart2.draw(g2, r2D);
                g2.dispose();
                cb.addTemplate(tp, 20, 350);
                document.close();
            } catch (Exception exc) {
            }
        }
    }
}
项目:evaluation    文件:EvalPDFReportBuilder.java   
/**
   * @param question
   *            the question text
   * @param choices
   *            the text for the choices
   * @param values
   *            the count of answers for each choice (same order as choices)
   * @param responseCount
   *            the number of responses to the question
   * @param showPercentages
   *            if true then show the percentages
   * @param answersAndMean
   *            the text which will be displayed above the chart (normally the answers count and
   *            mean)
   * @param lastElementIsHeader
   *            If the last element was a header, the extra spacing paragraph is not needed.
   */
  public void addLikertResponse(String question, String[] choices, int[] values,
          int responseCount, boolean showPercentages, String answersAndMean, boolean lastElementIsHeader)
  {
    ArrayList <Element> myElements = new ArrayList<>();

      try
      {
        if (!lastElementIsHeader)
        {
            Paragraph emptyPara = new Paragraph(" ");
            this.addElementWithJump(emptyPara, false);
        }

        Paragraph myPara = new Paragraph(question, questionTextFont);
        myPara.setSpacingAfter(SPACING_AFTER_HEADER);
        myElements.add(myPara);

    EvalLikertChartBuilder chartBuilder = new EvalLikertChartBuilder();
    chartBuilder.setValues(values);
    chartBuilder.setResponses(choices);
    chartBuilder.setShowPercentages(showPercentages);
    chartBuilder.setResponseCount(responseCount);
    JFreeChart chart = chartBuilder.makeLikertChart();

    /* The height is going to be based off the number of choices */
    int height = 15 * choices.length;

    PdfContentByte cb = pdfWriter.getDirectContent();
    PdfTemplate tp = cb.createTemplate(200, height);
    Graphics2D g2d = tp.createGraphics(200, height, new DefaultFontMapper());
    Rectangle2D r2d = new Rectangle2D.Double(0, 0, 200, height);
    chart.draw(g2d, r2d);
    g2d.dispose();
    Image image = Image.getInstance(tp);

    // put image in the document
    myElements.add(image);

    if (answersAndMean != null)
    {
        Paragraph header = new Paragraph(answersAndMean, paragraphFont);
        header.setSpacingAfter(SPACING_BETWEEN_LIST_ITEMS);
        myElements.add(header);
    }

    this.addElementArrayWithJump(myElements);
} catch (BadElementException e) {
    // TODO Auto-generated catch block
    LOG.warn( e );
}
  }
项目:metasfresh    文件:Document.java   
private static void writePDF(Pageable pageable, OutputStream output)
{
    try {
           final PageFormat pf = pageable.getPageFormat(0);

           final com.lowagie.text.Document document =
            new com.lowagie.text.Document(new Rectangle(
                    (int) pf.getWidth(), (int) pf.getHeight()));
           final PdfWriter writer = PdfWriter.getInstance(
                   document, output);
           writer.setPdfVersion(PdfWriter.VERSION_1_2);
           document.open();
           final DefaultFontMapper mapper = new DefaultFontMapper();     

           //Elaine 2009/02/17 - load additional font from directory set in PDF_FONT_DIR of System Configurator 
           String pdfFontDir = MSysConfig.getValue(PDF_FONT_DIR, ""); 
           if(pdfFontDir != null && pdfFontDir.trim().length() > 0)
           {
            pdfFontDir = pdfFontDir.trim();
            File dir = new File(pdfFontDir);
            if(dir.exists() && dir.isDirectory())
                mapper.insertDirectory(pdfFontDir);
           }
           //

           final float w = (float) pf.getWidth();
           final float h = (float) pf.getHeight();
           final PdfContentByte cb = writer.getDirectContent();
           for (int page = 0; page < pageable.getNumberOfPages(); page++) {
            if (page != 0) {
                document.newPage();
            }

            final PdfTemplate tp = cb.createTemplate(w, h);
            final Graphics2D g2 = tp.createGraphics(w, h, mapper);
            tp.setWidth(w);
            tp.setHeight(h);
            pageable.getPrintable(page).print(g2, pf, page);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
           }
           document.close();

       } catch (Exception e) {
           e.printStackTrace();
       }
}
项目:Openfire    文件:GraphServlet.java   
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[], Statistic[] stats, long starttime, long endtime, int width, int height)
        throws IOException
{

    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();



        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " +
                    JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph  = new Paragraph(serverName,
                FontFactory.getFont(FontFactory.HELVETICA,
                18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName,
                FontFactory.getFont(FontFactory.HELVETICA,
                14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                FontFactory.getFont(FontFactory.HELVETICA, 16,
                Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}
项目:kidneyExchange    文件:JFreeChartUtil.java   
public static void saveChartAsPDF(File file,
        JFreeChart chart,
        int width,
        int height) throws IOException {
    saveChartAsPDF(file,chart,width,height,new DefaultFontMapper());
}
项目:xfp    文件:StatisticsChartPaneTab.java   
/**
 * This method initializes jButton  
 *  
 * @return javax.swing.JButton      
 */    
private JButton getPrintButton()
    {
    if (printButton == null)
        {
        printButton = new JButton();
        printButton.setText("Export to PDF...");
        final JFreeChart chart = chartPane.getChart(); 
        printButton.addActionListener(new java.awt.event.ActionListener()
            { 
            public void actionPerformed(java.awt.event.ActionEvent e)
                {    
                try

                    {
                    int width = chartPane.getWidth();
                    int height = chartPane.getHeight();

                    FileDialog fileDialog = new FileDialog(new Frame(),"Export...",FileDialog.SAVE);
                    fileDialog.setDirectory(System.getProperty("user.dir"));
                    fileDialog.setFile("*.pdf");
                    fileDialog.setVisible(true);
                    String fileName = fileDialog.getFile();
                    if ( fileName != null )

                        {
                        if (!fileName.endsWith(".pdf"))
                            {
                            fileName = fileName+".pdf";
                            }
                        File f = new File(fileDialog.getDirectory(), fileName);
                        Document document = new Document(new com.lowagie.text.Rectangle(width,height));
                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
                        document.addAuthor("ECJ Console");
                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(width, height);
                        Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
                        chart.draw(g2, rectangle2D);
                        g2.dispose();
                        cb.addTemplate(tp, 0, 0);
                        document.close();
                        }
                    }
                catch( Exception ex )

                    {
                    ex.printStackTrace();
                    }
                }
            });
        }
    return printButton;
    }
项目:PDFReporter    文件:Page.java   
Page(PdfContentByte content) {
    this.delegate = content;
    this.fontmapper = new DefaultFontMapper();
}
项目:openfire    文件:GraphServlet.java   
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[], Statistic[] stats, long starttime, long endtime, int width, int height)
        throws IOException
{

    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();



        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " +
                    JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph  = new Paragraph(serverName,
                FontFactory.getFont(FontFactory.HELVETICA,
                18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName,
                FontFactory.getFont(FontFactory.HELVETICA,
                14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                FontFactory.getFont(FontFactory.HELVETICA, 16,
                Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}
项目:openfire-bespoke    文件:GraphServlet.java   
private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[], Statistic[] stats, long starttime, long endtime, int width, int height)
        throws IOException
{

    try {
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();



        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - " +
                    JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph  = new Paragraph(serverName,
                FontFactory.getFont(FontFactory.HELVETICA,
                18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName,
                FontFactory.getFont(FontFactory.HELVETICA,
                14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                FontFactory.getFont(FontFactory.HELVETICA, 16,
                Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}