Java Code Examples for java.awt.print.PageFormat#getHeight()

The following examples show how to use java.awt.print.PageFormat#getHeight() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Pages.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public Dimension getPreferredSize() {
  final PrintPage[][] pages = this.parent.getPages();
  final PageFormat thePageFormat = this.parent.getPageFormat();
  final double scale = this.parent.getScale();

  int pagesAtHorizontal = 0;
  int pagesAtVertical = pages.length;

  final double paperWidth = thePageFormat.getWidth();
  final double paperHeight = thePageFormat.getHeight();

  for (final PrintPage[] row : pages) {
    pagesAtHorizontal = Math.max(pagesAtHorizontal, row.length);
  }

  final int width = (int) Math.round(INTERVAL_X + ((paperWidth + INTERVAL_X) * pagesAtHorizontal));
  final int height = (int) Math.round(INTERVAL_Y + ((paperHeight + INTERVAL_Y) * pagesAtVertical));

  return new Dimension((int) Math.round(width * scale), (int) Math.round(height * scale));
}
 
Example 2
Source File: PrintLayout.java    From pumpernickel with MIT License 6 votes vote down vote up
/**
 * This describes a <code>PageFormat</code> as a String. This is provided as
 * a debugging tool, because <code>PageFormat.toString()</code> doesn't
 * support this itself.
 */
public static String toString(PageFormat f) {
	if (f == null)
		return "null";
	String orientation;
	if (f.getOrientation() == PageFormat.LANDSCAPE) {
		orientation = "LANDSCAPE";
	} else if (f.getOrientation() == PageFormat.PORTRAIT) {
		orientation = "PORTRAIT";
	} else if (f.getOrientation() == PageFormat.REVERSE_LANDSCAPE) {
		orientation = "REVERSE_LANDSCAPE";
	} else {
		orientation = "UNKNOWN";
	}
	return ("PageFormat[ " + f.getWidth() + "x" + f.getHeight()
			+ " imageable=(" + f.getImageableX() + ", " + f.getImageableY()
			+ ", " + f.getImageableWidth() + ", " + f.getImageableHeight()
			+ ") orientation=" + orientation + "]");
}
 
Example 3
Source File: PrintablePaintable.java    From pumpernickel with MIT License 6 votes vote down vote up
public int print(Graphics g, PageFormat pageFormat, int pageIndex)
		throws PrinterException {
	if (pageIndex >= pages.length)
		return Printable.NO_SUCH_PAGE;

	Paintable paintable = pages[pageIndex];
	double pWidth = paintable.getWidth();
	double pHeight = paintable.getHeight();

	double wRatio = pageFormat.getWidth() / pWidth;
	double hRatio = pageFormat.getHeight() / pHeight;
	double zoom = Math.min(wRatio, hRatio);

	Graphics2D g2 = (Graphics2D) g.create();
	g2.translate(pageFormat.getWidth() / 2 - pWidth * zoom / 2,
			pageFormat.getHeight() / 2 - pHeight * zoom / 2);
	g2.scale(zoom, zoom);

	paintable.paint(g2);

	return Printable.PAGE_EXISTS;
}
 
Example 4
Source File: DrawVisitorPrintable.java    From Gaalop with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    DrawVisitorGraphics drawVisitorGraphics = new DrawVisitorGraphics(world, (int) (pageFormat.getWidth()), (int) (pageFormat.getHeight()));
    drawVisitorGraphics.setGraphics(graphics);
    drawing.draw(drawVisitorGraphics);
    return (pageIndex == 0) ? Printable.PAGE_EXISTS : Printable.NO_SUCH_PAGE;
}
 
Example 5
Source File: PageFormatFactory.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Insets getPageMargins( final PageFormat format ) {

    final int marginLeft = (int) format.getImageableX();
    final int marginRight = (int) ( format.getWidth() - format.getImageableWidth() - format.getImageableX() );
    final int marginTop = (int) ( format.getImageableY() );
    final int marginBottom = (int) ( format.getHeight() - format.getImageableHeight() - format.getImageableY() );
    return new Insets( marginTop, marginLeft, marginBottom, marginRight );
  }
 
Example 6
Source File: PageFormatPreviewPane.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Dimension getPreferredSize() {
  if ( pageDefinition == null ) {
    return new Dimension();
  }

  final PageFormat pageFormat = getPageFormat();
  return new Dimension( (int) pageFormat.getWidth(), (int) pageFormat.getHeight() );
}
 
Example 7
Source File: PageReadHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Handles the page format.
 *
 * @param atts
 *          the attributes.
 * @throws SAXException
 *           if a parser error occurs or the validation failed.
 * @noinspection SuspiciousNameCombination
 */
private void handlePageFormat( final Attributes atts ) throws SAXException {
  final MasterReport report =
      (MasterReport) getRootHandler().getHelperObject( ReportParserUtil.HELPER_OBJ_REPORT_NAME );

  // grab the default page definition ...
  PageFormat format = report.getPageDefinition().getPageFormat( 0 );
  float defTopMargin = (float) format.getImageableY();
  float defBottomMargin = (float) ( format.getHeight() - format.getImageableHeight() - format.getImageableY() );
  float defLeftMargin = (float) format.getImageableX();
  float defRightMargin = (float) ( format.getWidth() - format.getImageableWidth() - format.getImageableX() );

  format = createPageFormat( format, atts );

  defTopMargin = ParserUtil.parseFloat( atts.getValue( getUri(), PageReadHandler.TOPMARGIN_ATT ), defTopMargin );
  defBottomMargin =
      ParserUtil.parseFloat( atts.getValue( getUri(), PageReadHandler.BOTTOMMARGIN_ATT ), defBottomMargin );
  defLeftMargin = ParserUtil.parseFloat( atts.getValue( getUri(), PageReadHandler.LEFTMARGIN_ATT ), defLeftMargin );
  defRightMargin = ParserUtil.parseFloat( atts.getValue( getUri(), PageReadHandler.RIGHTMARGIN_ATT ), defRightMargin );

  final Paper p = format.getPaper();
  switch ( format.getOrientation() ) {
    case PageFormat.PORTRAIT:
      PageFormatFactory.getInstance().setBorders( p, defTopMargin, defLeftMargin, defBottomMargin, defRightMargin );
      break;
    case PageFormat.LANDSCAPE:
      // right, top, left, bottom
      PageFormatFactory.getInstance().setBorders( p, defRightMargin, defTopMargin, defLeftMargin, defBottomMargin );
      break;
    case PageFormat.REVERSE_LANDSCAPE:
      PageFormatFactory.getInstance().setBorders( p, defLeftMargin, defBottomMargin, defRightMargin, defTopMargin );
      break;
    default:
      // will not happen..
      throw new IllegalArgumentException( "Unexpected paper orientation." );
  }

  format.setPaper( p );
  pageFormat = format;
}
 
Example 8
Source File: PageDefinitionReadHandler.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Handles the page format.
 *
 * @param atts
 *          the attributes.
 * @throws SAXException
 *           if a parser error occurs or the validation failed.
 * @noinspection SuspiciousNameCombination
 */
private PageFormat configurePageSizeAndMargins( final Attributes atts, PageFormat format ) throws SAXException {
  // (1) Grab the existing default ...
  float defTopMargin = (float) format.getImageableY();
  float defBottomMargin = (float) ( format.getHeight() - format.getImageableHeight() - format.getImageableY() );
  float defLeftMargin = (float) format.getImageableX();
  float defRightMargin = (float) ( format.getWidth() - format.getImageableWidth() - format.getImageableX() );

  // (2) Now configure the new paper-size
  format = configurePageSize( format, atts );

  // (3) Reconfigure margins as requested
  defTopMargin = ParserUtil.parseFloat( atts.getValue( getUri(), "margin-top" ), defTopMargin );
  defBottomMargin = ParserUtil.parseFloat( atts.getValue( getUri(), "margin-bottom" ), defBottomMargin );
  defLeftMargin = ParserUtil.parseFloat( atts.getValue( getUri(), "margin-left" ), defLeftMargin );
  defRightMargin = ParserUtil.parseFloat( atts.getValue( getUri(), "margin-right" ), defRightMargin );

  final Paper p = format.getPaper();
  switch ( format.getOrientation() ) {
    case PageFormat.PORTRAIT:
      PageFormatFactory.getInstance().setBorders( p, defTopMargin, defLeftMargin, defBottomMargin, defRightMargin );
      break;
    case PageFormat.REVERSE_LANDSCAPE:
      PageFormatFactory.getInstance().setBorders( p, defLeftMargin, defBottomMargin, defRightMargin, defTopMargin );
      break;
    case PageFormat.LANDSCAPE:
      PageFormatFactory.getInstance().setBorders( p, defRightMargin, defTopMargin, defLeftMargin, defBottomMargin );
      break;
    default:
      // will not happen..
      throw new IllegalArgumentException( "Unexpected paper orientation." );
  }

  format.setPaper( p );
  return format;
}
 
Example 9
Source File: StraightToPNG.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create the empty image for the given page size.
 *
 * @param pd the page definition that defines the image bounds.
 * @return the generated image.
 */
private BufferedImage createImage(final PageDefinition pd)
{
  // in this simple case we know, that all pages have the same size..
  final PageFormat pf = pd.getPageFormat(0);

  final double width = pf.getWidth();
  final double height = pf.getHeight();
  //write the report to the temp file
  return new BufferedImage
      ((int) width, (int) height, BufferedImage.TYPE_BYTE_INDEXED);
}
 
Example 10
Source File: StyleSheetUtility.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void updateRuleForPage( final CSSPageRule rule,
                                      final PageFormat format ) {
  if ( format == null ) {
    rule.removeProperty( BoxStyleKeys.MARGIN_TOP );
    rule.removeProperty( BoxStyleKeys.MARGIN_LEFT );
    rule.removeProperty( BoxStyleKeys.MARGIN_BOTTOM );
    rule.removeProperty( BoxStyleKeys.MARGIN_RIGHT );
    rule.removeProperty( PageStyleKeys.SIZE );
    //      rule.removeProperty(PageStyleKeys.HORIZONTAL_PAGE_SPAN);
    //      rule.removeProperty(PageStyleKeys.VERTICAL_PAGE_SPAN);
    return;
  }


  final double width = format.getWidth();
  final double height = format.getHeight();
  rule.setPropertyValueAsString( PageStyleKeys.SIZE,
    width + "pt " + height + "pt" );
  rule.setPropertyValueAsString( BoxStyleKeys.MARGIN_TOP, format.getImageableY() + "pt" );
  rule.setPropertyValueAsString( BoxStyleKeys.MARGIN_LEFT, format.getImageableX() + "pt" );

  final double marginRight = width - format.getImageableX() - format.getImageableWidth();
  final double marginBottom = height - format.getImageableY() - format.getImageableHeight();
  rule.setPropertyValueAsString( BoxStyleKeys.MARGIN_BOTTOM, marginBottom + "pt" );
  rule.setPropertyValueAsString( BoxStyleKeys.MARGIN_RIGHT, marginRight + "pt" );
  //    rule.setPropertyValueAsString(PageStyleKeys.HORIZONTAL_PAGE_SPAN, "1");
  //    rule.setPropertyValueAsString(PageStyleKeys.VERTICAL_PAGE_SPAN, "1");
}
 
Example 11
Source File: PrintPreviewDialog.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    double px = pf.getWidth();
    double py = pf.getHeight();
    double sx = getWidth() - 1;
    double sy = getHeight() - 1;
    double xoff;
    double yoff;
    double scale;
    if(px / py < sx / sy)
    {
        scale = sy / py;
        xoff = 0.5D * (sx - scale * px);
        yoff = 0.0D;
    } else
    {
        scale = sx / px;
        xoff = 0.0D;
        yoff = 0.5D * (sy - scale * py);
    }
    g2.translate((float)xoff, (float)yoff);
    g2.scale((float)scale, (float)scale);
    Rectangle2D page = new Rectangle2D.Double(0.0D, 0.0D, px, py);
    g2.setPaint(Color.white);
    g2.fill(page);
    g2.setPaint(Color.black);
    g2.draw(page);
    try
    {
        preview.print(g2, pf, currentPage);
    }
    catch(PrinterException pe)
    {
        g2.draw(new java.awt.geom.Line2D.Double(0.0D, 0.0D, px, py));
        g2.draw(new java.awt.geom.Line2D.Double(0.0D, px, 0.0D, py));
    }
}
 
Example 12
Source File: LocatePrint.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
public void PrintText(Graphics2D g2,String printStr,Font t,float printX,float printY,PageFormat pf)
{
	//英寸
	float Printx=(float)(printX/25.4-(float)(pf.getWidth()-pf.getImageableWidth())/144)*72;
	float Printy=(float)(printY/25.4-(float)(pf.getHeight()-pf.getImageableHeight())/144)*72;
	if (Printx<0 )
	{
		Printx=0;
	}

    g2.drawString(printStr,Printx,Printy);
  
}
 
Example 13
Source File: PrintPreviewComponent.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
public Dimension2D getPageSize() {
    int pageCount = printable.getPageCount();
    double pageWidth = 0;
    double pageHeight = 0;
    PageFormat pageFormat = new PageFormat();
    for (int i = 0; i < pageCount; i++) {
        pageFormat = printable.getPageFormat(pageFormat, i);
        double w = pageFormat.getWidth();
        double h = pageFormat.getHeight();

        if (pageWidth < w)
            pageWidth = w;
        if (pageHeight < h)
            pageHeight = h;
    }

    final double fw = pageWidth;
    final double fh = pageHeight;
    return new Dimension2D() {

        @Override
        public void setSize(double width, double height) {
        }

        @Override
        public double getWidth() {
            return fw;
        }

        @Override
        public double getHeight() {
            return fh;
        }
    };
}
 
Example 14
Source File: PrintPreviewComponent.java    From ramus with GNU General Public License v3.0 4 votes vote down vote up
private void setSize() {
     int pageCount = printable.getPageCount();
     rowCount = (pageCount - 1) / columnCount + 1;
     pageWidth = 0;
     pageHeight = 0;
     pages = new Page[pageCount];
     PageFormat pageFormat = printable.getPageFormat();
     for (int i = 0; i < pageCount; i++) {
         pageFormat = printable.getPageFormat(pageFormat, i);
         double w = pageFormat.getWidth() + 1;
         double h = pageFormat.getHeight() + 1;
         double iW = pageFormat.getImageableWidth();
         double iH = pageFormat.getImageableHeight();
         double x = pageFormat.getImageableX();
         double y = pageFormat.getImageableY();

         reverce = (pageFormat.getOrientation() == PageFormat.REVERSE_LANDSCAPE);

/*
          * if (pageFormat.getOrientation() == PageFormat.LANDSCAPE) { double
 * t;
 * 
 * t = w; w = h; h = t;
 * 
 * t = iW; iW = iH; iH = t;
 * 
 * t = x; x = y; y = t; }
 */

         Page page = new Page(w, h, x, y, iW, iH);

         if (pageWidth < w)
             pageWidth = w;
         if (pageHeight < h)
             pageHeight = h;
         pages[i] = page;
     }
     width = (columnCount - 1) * (pageWidth + W_SPACE / zoom) + pageWidth;
     height = rowCount * (pageHeight + W_SPACE / zoom);
     Dimension size = new Dimension((int) (width * getZoom()),
             (int) (height * getZoom()));
     this.setSize(size);
     this.setPreferredSize(size);
 }
 
Example 15
Source File: Pages.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void paint(@Nonnull final Graphics g) {
  final Graphics2D gfx = (Graphics2D) g;
  gfx.setColor(parent.isDarkTheme() ? Color.DARK_GRAY : Color.LIGHT_GRAY);
  final Dimension size = getSize();
  gfx.fillRect(0, 0, size.width, size.height);

  final double scale = this.parent.getScale();
  final PageFormat thePageFormat = this.parent.getPageFormat();

  final PrintPage[][] allPages = this.parent.getPages();

  final double PAGE_WIDTH = thePageFormat.getWidth();
  final double PAGE_HEIGHT = thePageFormat.getHeight();

  final double AREA_WIDTH = thePageFormat.getImageableWidth();
  final double AREA_HEIGHT = thePageFormat.getImageableHeight();

  final Rectangle2D pageBack = new Rectangle2D.Double(0.0d, 0.0d, PAGE_WIDTH, PAGE_HEIGHT);
  final Rectangle2D pageArea = new Rectangle2D.Double(0.0d, 0.0d, AREA_WIDTH, AREA_HEIGHT);

  final Color SHADOW = new Color(0, 0, 0, 0x50);

  int y = INTERVAL_Y;

  final double AREA_X = thePageFormat.getImageableX();
  final double AREA_Y = thePageFormat.getImageableY();

  final boolean drawBorder = this.parent.isDrawBorder();

  gfx.scale(scale, scale);
  for (final PrintPage[] pages : allPages) {
    int x = INTERVAL_X;
    for (final PrintPage p : pages) {
      gfx.translate(x, y);

      gfx.setColor(SHADOW);
      pageBack.setRect(SHADOW_X, SHADOW_Y, pageBack.getWidth(), pageBack.getHeight());
      gfx.fill(pageBack);
      gfx.setColor(Color.WHITE);
      pageBack.setRect(0.0d, 0.0d, pageBack.getWidth(), pageBack.getHeight());
      gfx.fill(pageBack);

      gfx.translate(AREA_X, AREA_Y);

      final Graphics2D gfxCopy = (Graphics2D) gfx.create();
      gfxCopy.clip(pageArea);
      p.print(gfxCopy);
      gfxCopy.dispose();

      if (drawBorder) {
        final Stroke oldStroke = gfx.getStroke();
        gfx.setColor(MMDPrintPanel.BORDER_COLOR);
        gfx.setStroke(MMDPrintPanel.BORDER_STYLE);
        gfx.draw(pageArea);
        gfx.setStroke(oldStroke);
      }

      gfx.translate(-AREA_X, -AREA_Y);

      gfx.translate(-x, -y);
      x += INTERVAL_X + PAGE_WIDTH;
    }
    y += INTERVAL_Y + PAGE_HEIGHT;
  }
  gfx.scale(1.0d, 1.0d);

  paintBorder(g);
}
 
Example 16
Source File: PreviewCanvas.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    double px = pf.getWidth();
    double py = pf.getHeight();
    double sx = getWidth() - 1;
    double sy = getHeight() - 1;
    double xoff;
    double yoff;
    double scale;
    if(px / py < sx / sy)
    {
        scale = sy / py;
        xoff = 0.5D * (sx - scale * px);
        yoff = 0.0D;
    } else
    {
        scale = sx / px;
        xoff = 0.0D;
        yoff = 0.5D * (sy - scale * py);
    }
    g2.translate((float)xoff, (float)yoff);
    g2.scale((float)scale, (float)scale);
   // Rectangle2D page=new 
    Rectangle2D page = new Rectangle2D.Double(0.0D, 0.0D, px, py);
    g2.setPaint(Color.white);
    g2.fill(page);
    g2.setPaint(Color.black);
    g2.draw(page);
    try
    {
        preview.print(g2, pf, currentPage);
    }
    catch(PrinterException pe)
    {
        g2.draw(new Rectangle2D.Double(0.0D, 0.0D, px, py));
        g2.draw(new Rectangle2D.Double(0.0D, px, 0.0D, py));
    }
}
 
Example 17
Source File: CharacterSheet.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * @param path         The path to save to.
 * @param createdPaths The paths that were created.
 * @return {@code true} on success.
 */
public boolean saveAsPNG(Path path, List<Path> createdPaths) {
    Set<Row> changed = expandAllContainers();
    try {
        int          dpi      = Preferences.getInstance().getPNGResolution();
        PrintManager settings = mCharacter.getPageSettings();
        PageFormat   format   = settings != null ? settings.createPageFormat() : createDefaultPageFormat();
        int          width    = (int) (format.getWidth() / 72.0 * dpi);
        int          height   = (int) (format.getHeight() / 72.0 * dpi);
        Img          buffer   = Img.create(width, height, Transparency.OPAQUE);
        int          pageNum  = 0;
        String       name     = PathUtils.getLeafName(path, false);

        path = path.getParent();

        adjustToPageSetupChanges(true);
        setPrinting(true);

        while (true) {
            File pngFile;

            Graphics2D gc = buffer.getGraphics();
            if (print(gc, format, pageNum) == NO_SUCH_PAGE) {
                gc.dispose();
                break;
            }
            gc.setClip(0, 0, width, height);
            gc.setBackground(Color.WHITE);
            gc.clearRect(0, 0, width, height);
            gc.scale(dpi / 72.0, dpi / 72.0);
            print(gc, format, pageNum++);
            gc.dispose();
            Path pngPath = path.resolve(PathUtils.enforceExtension(name + (pageNum > 1 ? " " + pageNum : ""), FileType.PNG.getExtension()));
            ImageIO.write(buffer, "png", pngPath.toFile());
            createdPaths.add(pngPath);
        }
        return true;
    } catch (Exception exception) {
        Log.error(exception);
        return false;
    } finally {
        setPrinting(false);
        closeContainers(changed);
    }
}
 
Example 18
Source File: CharacterSheet.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * @param path The path to save to.
 * @return {@code true} on success.
 */
public boolean saveAsPDF(Path path) {
    Set<Row> changed = expandAllContainers();
    try {
        PrintManager settings = mCharacter.getPageSettings();
        PageFormat   format   = settings != null ? settings.createPageFormat() : createDefaultPageFormat();
        float        width    = (float) format.getWidth();
        float        height   = (float) format.getHeight();

        adjustToPageSetupChanges(true);
        setPrinting(true);

        com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(new com.lowagie.text.Rectangle(width, height));
        try (OutputStream out = Files.newOutputStream(path)) {
            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) {
        Log.error(exception);
        return false;
    } finally {
        setPrinting(false);
        closeContainers(changed);
    }
}
 
Example 19
Source File: PageBackgroundDrawable.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Draws the object.
 *
 * @param graphics
 *          the graphics device.
 * @param area
 *          the area inside which the object should be drawn.
 */
public strictfp void draw( final Graphics2D graphics, final Rectangle2D area ) {
  if ( backend == null ) {
    return;
  }

  final PageFormat pageFormat = backend.getPageFormat();
  final float outerW = (float) pageFormat.getWidth();
  final float outerH = (float) pageFormat.getHeight();

  final float innerX = (float) pageFormat.getImageableX();
  final float innerY = (float) pageFormat.getImageableY();
  final float innerW = (float) pageFormat.getImageableWidth();
  final float innerH = (float) pageFormat.getImageableHeight();

  final Graphics2D g2 = (Graphics2D) graphics.create();
  // double paperBorder = paperBorderPixel * zoomFactor;

  /** Prepare background **/
  g2.transform( AffineTransform.getScaleInstance( getZoom(), getZoom() ) );
  g2.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON );

  /** Prepare background **/
  final Rectangle2D pageArea = new Rectangle2D.Float( 0, 0, outerW, outerH );
  /**
   * The border around the printable area is painted when the corresponding property is set to true.
   */
  final Rectangle2D printingArea = new Rectangle2D.Float( innerX, innerY, innerW, innerH );

  /** Paint Page Shadow */
  final Rectangle2D southborder = new Rectangle2D.Float( getShadowSize(), outerH, outerW, getShadowSize() );
  final Rectangle2D eastborder = new Rectangle2D.Float( outerW, getShadowSize(), getShadowSize(), outerH );

  g2.setPaint( UIManager.getColor( "controlShadow" ) ); //$NON-NLS-1$

  g2.fill( southborder );
  g2.fill( eastborder );

  if ( isBorderPainted() ) {
    g2.setPaint( Color.gray );
    g2.draw( printingArea );
  }

  g2.setPaint( Color.white );
  g2.fill( pageArea );

  final Graphics2D g22 = (Graphics2D) g2.create();
  backend.draw( g22, new Rectangle2D.Double( 0, 0, pageFormat.getWidth(), pageFormat.getHeight() ) );
  g22.dispose();

  final Rectangle2D transPageArea = new Rectangle2D.Float( 0, 0, outerW, outerH );
  g2.setPaint( Color.black );
  g2.draw( transPageArea );

  g2.dispose();
}
 
Example 20
Source File: ExportHighCharts.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException {

		Rectangle pageSize = PageSize.A4;
		Document document = new Document(pageSize);
		int orientation = PageFormat.PORTRAIT;
		try {
			PdfWriter writer = PdfWriter.getInstance(document, outputStream);
			document.open();

			double a4WidthInch = 8.26771654; // Equals 210mm
			double a4HeightInch = 11.6929134; // Equals 297mm

			Paper paper = new Paper();
			// 72 DPI
			paper.setSize((a4WidthInch * 72), (a4HeightInch * 72));
			// 1 inch margins
			paper.setImageableArea(72, 72, (a4WidthInch * 72 - 144), (a4HeightInch * 72 - 144));
			PageFormat pageFormat = new PageFormat();
			pageFormat.setPaper(paper);
			pageFormat.setOrientation(orientation);

			float width = ((float) pageFormat.getWidth());
			float height = ((float) pageFormat.getHeight());

			PdfContentByte cb = writer.getDirectContent();
			PdfTemplate template = cb.createTemplate(width, height);
			Graphics2D g2 = template.createGraphics(width, height);

			PrintTranscoder prm = new PrintTranscoder();
			TranscoderInput ti = new TranscoderInput(inputStream);
			prm.transcode(ti, null);

			prm.print(g2, pageFormat, 0);
			g2.dispose();

			ImgTemplate img = new ImgTemplate(template);
			img.setWidthPercentage(100);
			img.setAlignment(Image.ALIGN_CENTER);

			document.add(img);

		} catch (DocumentException e) {
			logger.error("Error exporting Highcharts to PDF: " + e);
		}
		document.close();
	}