コード例 #1
0
          @Override
          public void emitLinearFrame(
              Vector3 a,
              Vector3 b,
              java.util.List<Object> name,
              java.util.List<Object> name2,
              Dict properties,
              iLinearGraphicsContext contex) {
            Vector4 outputTransform = SimplePDFLineDrawing_3d.this.outputTransform;
            if (properties.isTrue(iLinearGraphicsContext.noTransform, false))
              outputTransform = new Vector4(1, 1, 0, 0);

            setStrokeProperties(name, properties);
            if (firstOut || lastOut.distanceFrom(a) > 1e-5) {
              Vector2 at = transform(a);
              path.moveTo(at.x, at.y);
              firstOut = false;
              lastOut = new Vector3(b);
            }
            Vector2 at = transform(b);

            ; // System.out.println(" line to <"+b+" -> "+at);
            if (!shouldClip) path.lineTo(at.x, at.y);
            lastOut.x = b.x;
            lastOut.y = b.y;
          }
コード例 #2
0
          @Override
          public void emitLinearFrame(
              Vector3 a,
              Vector3 b,
              java.util.List<Object> name,
              java.util.List<Object> name2,
              Dict properties,
              iLinearGraphicsContext contex) {
            if (firstOut || lastOut.distanceFrom(a) > 1e-2) {

              Plain3dPDFLine.this.context.getOutput().stroke();
              Plain3dPDFLine.this.context.getOutput().newPath();

              Vector2 at = transform(a);

              path.moveTo(at.x, at.y);
              setStrokeProperties(name, properties);
              firstOut = false;
              lastOut = new Vector3(b);
            }

            Vector2 at = transform(b);
            if (!shouldClip) {
              path.lineTo(at.x, at.y);
            }
            lastOut.x = b.x;
            lastOut.y = b.y;
            lastOut.z = b.z;
          }
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
      try {
        Rectangle page = document.getPageSize();

        getHeaderFooter(document);
        // Add page header
        header.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        header.writeSelectedRows(
            0, -1, document.leftMargin(), page.getHeight() - 10, writer.getDirectContent());

        // Add page footer
        footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
        footer.writeSelectedRows(
            0, -1, document.leftMargin(), document.bottomMargin() - 5, writer.getDirectContent());

        // Add page border

        int bmargin = 8; // border margin
        PdfContentByte cb = writer.getDirectContent();
        cb.rectangle(
            bmargin, bmargin, page.getWidth() - bmargin * 2, page.getHeight() - bmargin * 2);
        cb.setColorStroke(Color.LIGHT_GRAY);
        cb.stroke();

      } catch (JSONException e) {
        Logger.getLogger(ExportProjectReportServlet.class.getName()).log(Level.SEVERE, null, e);
        throw new ExceptionConverter(e);
      }
    }
コード例 #4
0
          protected void setStrokeProperties(List<Object> name, Dict properties) {

            Vector4 color = (Vector4) name.get(1);
            if (color == null) color = properties.get(iLinearGraphicsContext.fillColor);
            if (color == null) color = properties.get(iLinearGraphicsContext.color);
            if (color == null) color = black;

            float thick = widthFor(context, properties);

            thick = remapProperties(color = new Vector4(color), null, thick);

            PdfContentByte o = context.getOutput();

            o.setColorFill(new Color(clamp(color.x), clamp(color.y), clamp(color.z)));

            if (opName.equals("Opaque")) {
              PdfGState gs1 = new PdfGState();
              gs1.setFillOpacity(1);
              gs1.setStrokeOpacity(1);
              gs1.setBlendMode(new PdfName("Normal"));
              o.setGState(gs1);
            }
            {
              PdfGState gs1 = new PdfGState();
              gs1.setFillOpacity(color.w);
              gs1.setStrokeOpacity(color.w);
              gs1.setBlendMode(new PdfName(opName));
              o.setGState(gs1);
            }
          }
コード例 #5
0
ファイル: PlotPanel.java プロジェクト: scalalab/scalalab
  public void toPDFGraphicFile(File file, int width, int height) throws IOException {
    // otherwise toolbar appears
    plotToolBar.setVisible(false);

    com.lowagie.text.Document document = new com.lowagie.text.Document();
    document.setPageSize(new Rectangle(width, height));
    FileOutputStream fos = new FileOutputStream(file);

    PdfWriter writer = null;
    try {
      writer = PdfWriter.getInstance(document, fos);
    } catch (DocumentException ex) {
      Logger.getLogger(PlotPanel.class.getName()).log(Level.SEVERE, null, ex);
    }
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfTemplate tp = cb.createTemplate(width, height);
    Graphics2D g2d = tp.createGraphics(width, height);

    Image image = createImage(getWidth(), getHeight());
    paint(image.getGraphics());
    image = new ImageIcon(image).getImage();

    g2d.drawImage(image, 0, 0, Color.WHITE, null);
    g2d.dispose();
    cb.addTemplate(tp, 1, 0, 0, 1, 0, 0);

    document.close();
    // make it reappear
    plotToolBar.setVisible(true);
  }
コード例 #6
0
  /**
   * Método que dibuja el número de página.
   *
   * @param writer Creador de documentos.
   * @param document Documento del informe.
   */
  public void drawPageNumber(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    // Número de página
    String text =
        new StringBuffer()
            .append("Página ")
            .append(writer.getPageNumber())
            .append(" de ")
            .toString();

    float textSize = HELVETICA.getWidthPoint(text, 8);
    float textBase = document.bottom() - 20;

    cb.beginText();
    cb.setColorFill(FOOTER_COLOR);
    cb.setFontAndSize(HELVETICA, 8);
    cb.setTextMatrix(document.right() - textSize - 20, textBase);
    cb.showText(text);
    cb.endText();
    cb.addTemplate(tpl, document.right() - 20, textBase);

    cb.restoreState();
  }
コード例 #7
0
ファイル: PDF.java プロジェクト: ringgi/railo
  private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    railo.runtime.img.Image ri =
        new railo.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
コード例 #8
0
ファイル: SgtUtil.java プロジェクト: BobSimons/erddap
  /**
   * This closes the pdf file created by createPDF, after you have written things to g2D.
   *
   * @param oar the object[] returned from createPdf
   * @throwsException if trouble
   */
  public static void closePdf(Object oar[]) throws Exception {
    Graphics2D g2D = (Graphics2D) oar[0];
    Document document = (Document) oar[1];
    PdfContentByte pdfContentByte = (PdfContentByte) oar[2];
    PdfTemplate pdfTemplate = (PdfTemplate) oar[3];

    g2D.dispose();

    // center it
    if (verbose)
      String2.log(
          "SgtUtil.closePdf"
              + " left="
              + document.left()
              + " right="
              + document.right()
              + " bottom="
              + document.bottom()
              + " top="
              + document.top()
              + " template.width="
              + pdfTemplate.getWidth()
              + " template.height="
              + pdfTemplate.getHeight());
    // x device = ax user + by user + e
    // y device = cx user + dy user + f
    pdfContentByte.addTemplate(
        pdfTemplate, // a,b,c,d,e,f      //x,y location in points
        0.5f,
        0,
        0,
        0.5f,
        document.left() + (document.right() - document.left() - pdfTemplate.getWidth() / 2) / 2,
        document.bottom() + (document.top() - document.bottom() - pdfTemplate.getHeight() / 2) / 2);

    /*
    //if boundingBox is small, center it
    //if boundingBox is large, shrink and center it
    //document.left/right/top/bottom include 1/2" margins
    float xScale = (document.right() - document.left())   / pdfTemplate.getWidth();
    float yScale = (document.top()   - document.bottom()) / pdfTemplate.getHeight();
    float scale = Math.min(Math.min(xScale, yScale), 1);
    float xSize = pdfTemplate.getWidth()  / scale;
    float ySize = pdfTemplate.getHeight() / scale;
    //x device = ax user + by user + e
    //y device = cx user + dy user + f
    pdfContentByte.addTemplate(pdfTemplate, //a,b,c,d,e,f
        scale, 0, 0, scale,
        document.left()   + (document.right() - document.left()   - xSize) / 2,
        document.bottom() + (document.top()   - document.bottom() - ySize) / 2);
    */

    document.close();
  }
コード例 #9
0
ファイル: UIChart.java プロジェクト: subaochen/seam
  @Override
  public void createITextObject(FacesContext context) {

    if (getBorderBackgroundPaint() != null) {
      chart.setBackgroundPaint(findColor(getBorderBackgroundPaint()));
    }

    if (getBorderPaint() != null) {
      chart.setBorderPaint(findColor(getBorderPaint()));
    }

    if (getBorderStroke() != null) {
      chart.setBorderStroke(findStroke(getBorderStroke()));
    }

    chart.setBorderVisible(getBorderVisible());

    configurePlot(chart.getPlot());

    try {
      UIDocument doc = (UIDocument) findITextParent(getParent(), UIDocument.class);
      if (doc != null) {
        PdfWriter writer = (PdfWriter) doc.getWriter();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(getWidth(), getHeight());

        UIFont font = (UIFont) findITextParent(this, UIFont.class);

        DefaultFontMapper fontMapper;
        if (font == null) {
          fontMapper = new DefaultFontMapper();
        } else {
          fontMapper = new AsianFontMapper(font.getName(), font.getEncoding());
        }

        Graphics2D g2 = tp.createGraphics(getWidth(), getHeight(), fontMapper);
        chart.draw(g2, new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
        g2.dispose();

        image = new ImgTemplate(tp);
      } else {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ChartUtilities.writeChartAsJPEG(stream, chart, getWidth(), getHeight());

        imageData = stream.toByteArray();
        stream.close();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
コード例 #10
0
 public void encodeHeaderBox(PdfContentByte directContent, Bounds bounds, String title) {
   setFillColorBlack(directContent);
   Bounds headerBounds = calculateHeaderBounds(bounds);
   directContent.rectangle(
       headerBounds.x + ARCSPACE,
       headerBounds.y,
       headerBounds.width - 2 * ARCSPACE,
       headerBounds.height);
   directContent.arc(
       headerBounds.x,
       headerBounds.y,
       headerBounds.x + 2 * ARCSPACE,
       headerBounds.y + headerBounds.height,
       0,
       360);
   directContent.arc(
       headerBounds.getMaxX(),
       headerBounds.y,
       headerBounds.getMaxX() - 2 * ARCSPACE,
       headerBounds.getMaxY(),
       0,
       360);
   directContent.fillStroke();
   setFillColorWhite(directContent);
   directContent.setFontAndSize(baseFont, HEADER_FONT_SIZE);
   directContent.beginText();
   directContent.showTextAligned(
       PdfContentByte.ALIGN_CENTER,
       title,
       (int) headerBounds.getCenterX(),
       headerBounds.y + HEADER_FONT_PADDING,
       0);
   directContent.endText();
 }
コード例 #11
0
  /**
   * Método que dibuja el pie de la página.
   *
   * @param writer Creador de documentos.
   * @param document Documento del informe.
   */
  private void drawFooter(PdfWriter writer, Document document) {
    try {
      PdfContentByte cb = writer.getDirectContent();
      cb.saveState();

      PdfPTable table = new PdfPTable(2);
      table.setTotalWidth(new float[] {70, document.right() - document.left() - 70});
      table.setLockedWidth(true);
      table.setHorizontalAlignment(Element.ALIGN_CENTER);
      table.getDefaultCell().setBorder(Rectangle.BOX);
      table.getDefaultCell().setBorderWidth(0.1F);
      table.getDefaultCell().setBorderColor(BORDER_COLOR);
      table.getDefaultCell().setBackgroundColor(BACKGROUND_COLOR);
      table.getDefaultCell().setFixedHeight(45);
      table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      /*
       * Image logo = Image.getInstance(FOOTER_IMAGE_URL);
       * logo.setBorder(Rectangle.BOX); logo.setBorderWidth(0.1F);
       * logo.setBorderColor(BORDER_COLOR); table.addCell(logo);
       */
      table.addCell("");

      PdfPTable tableInfo = new PdfPTable(1);
      tableInfo.setTotalWidth(document.right() - document.left() - 75);
      tableInfo.setLockedWidth(true);
      tableInfo.setHorizontalAlignment(Element.ALIGN_CENTER);
      tableInfo.getDefaultCell().setBorder(Rectangle.NO_BORDER);
      tableInfo.getDefaultCell().setFixedHeight(20);
      tableInfo.getDefaultCell().setPadding(5);
      tableInfo.addCell(
          new Phrase(new Chunk(DateUtils.EXTENDED_DATE_FORMATTER.format(new Date()), FOOTER_FONT)));

      PdfPCell tableInfoCell = new PdfPCell(tableInfo.getDefaultCell());
      tableInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
      tableInfoCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
      tableInfoCell.setPhrase(new Phrase(new Chunk(DIRECCION, FOOTER_ITALIC_FONT)));
      tableInfo.addCell(tableInfoCell);
      table.addCell(tableInfo);

      table.writeSelectedRows(0, -1, document.left(), document.bottom() - 5, cb);

      cb.restoreState();
    } catch (Exception e) {
      throw new ExceptionConverter(e);
    }
  }
コード例 #12
0
 /**
  * Change the textMode() to either SHAPE or MODEL. <br>
  * This resets all renderer settings, and should therefore be called <EM>before</EM> any other
  * commands that set the fill() or the textFont() or anything. Unlike other renderers, use
  * textMode() directly after the size() command.
  */
 public void textMode(int mode) {
   if (textMode != mode) {
     if (mode == SHAPE) {
       g2.dispose();
       g2 = content.createGraphicsShapes(width, height);
     } else if (mode == MODEL) {
       g2.dispose();
       g2 = content.createGraphics(width, height, mapper);
       //        g2 = template.createGraphics(width, height, mapper);
     } else if (mode == SCREEN) {
       throw new RuntimeException("textMode(SCREEN) not supported with PDF");
     } else {
       throw new RuntimeException("That textMode() does not exist");
     }
   }
 }
コード例 #13
0
  public void beginDraw() {
    //    long t0 = System.currentTimeMillis();

    if (document == null) {
      document = new Document(new Rectangle(width, height));
      try {
        if (file != null) {
          // BufferedOutputStream output = new BufferedOutputStream(stream, 16384);
          output = new BufferedOutputStream(new FileOutputStream(file), 16384);

        } else if (output == null) {
          throw new RuntimeException(
              "PGraphicsPDF requires a path " + "for the location of the output file.");
        }
        writer = PdfWriter.getInstance(document, output);
        document.open();
        content = writer.getDirectContent();
        //        template = content.createTemplate(width, height);

      } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Problem saving the PDF file.");
      }

      //      System.out.println("beginDraw fonts " + (System.currentTimeMillis() - t));
      g2 = content.createGraphics(width, height, getMapper());
      //      g2 = template.createGraphics(width, height, mapper);
    }
    //    System.out.println("beginDraw " + (System.currentTimeMillis() - t0));
    super.beginDraw();
  }
コード例 #14
0
 public void onOpenDocument(PdfWriter writer, Document document) {
   try {
     cb = writer.getDirectContent();
     template = cb.createTemplate(50, 50);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
コード例 #15
0
 public void manipulatePdf(String src, String dest, int pow)
     throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   Rectangle pageSize = reader.getPageSize(1);
   Rectangle newSize =
       (pow % 2) == 0
           ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
           : new Rectangle(pageSize.getHeight(), pageSize.getWidth());
   Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
   for (int i = 0; i < pow; i++) {
     unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
   }
   int n = (int) Math.pow(2, pow);
   int r = (int) Math.pow(2, pow / 2);
   int c = n / r;
   Document document = new Document(newSize, 0, 0, 0, 0);
   PdfWriter writer =
       PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfImportedPage page;
   Rectangle currentSize;
   float offsetX, offsetY, factor;
   int total = reader.getNumberOfPages();
   for (int i = 0; i < total; ) {
     if (i % n == 0) {
       document.newPage();
     }
     currentSize = reader.getPageSize(++i);
     factor =
         Math.min(
             unitSize.getWidth() / currentSize.getWidth(),
             unitSize.getHeight() / currentSize.getHeight());
     offsetX =
         unitSize.getWidth() * ((i % n) % c)
             + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
     offsetY =
         newSize.getHeight()
             - (unitSize.getHeight() * (((i % n) / c) + 1))
             + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
     page = writer.getImportedPage(reader, i);
     cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
   }
   document.close();
 }
コード例 #16
0
 public static PdfTemplate createRectTemplate(
     PdfContentByte directContent, final Color strokeColor) {
   PdfTemplate activeHealthRect = directContent.createTemplate(HEALTH_RECT_SIZE, HEALTH_RECT_SIZE);
   activeHealthRect.setLineWidth(1f);
   activeHealthRect.setColorStroke(strokeColor);
   activeHealthRect.rectangle(0, 0, HEALTH_RECT_SIZE, HEALTH_RECT_SIZE);
   activeHealthRect.stroke();
   return activeHealthRect;
 }
コード例 #17
0
ファイル: ReaderPdf.java プロジェクト: alei76/excel-doc-pdf
  public static void main(String[] args) throws Exception {
    String filePath = ReaderPdf.class.getClassLoader().getResource("pdf/pdf.pdf").getPath();

    // 待加水印的文件
    PdfReader reader = new PdfReader(filePath);

    String newFilePath = "D:/test/newPdf.pdf";
    File f = new File(newFilePath);
    if (!f.exists()) {
      f.createNewFile();
    }

    // 加完水印的文件
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFilePath));
    int total = reader.getNumberOfPages() + 1;

    PdfContentByte content;
    // 设置字体
    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

    // BaseFont baseFont =
    // BaseFont.createFont("STSong-Light",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
    // BaseFont baseFont =
    // BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
    // 水印文字
    String waterText = "------广东省云浮市闻莺路东升布艺------";
    int leng = waterText.length(); // 文字长度
    char c = 0;
    int height = 0; // 高度
    // 循环对每页插入水印
    for (int i = 1; i < total; i++) {
      // 水印的起始
      height = 500;
      content = stamper.getUnderContent(i);
      // 开始
      content.beginText();
      // 设置颜色
      content.setColorFill(Color.GRAY);
      // 设置字体及字号
      content.setFontAndSize(baseFont, 18);
      // 设置起始位置
      content.setTextMatrix(500, 780);
      // 开始写入水印
      for (int k = 0; k < leng; k++) {
        content.setTextRise(14);
        c = waterText.charAt(k);
        // 将char转成字符串
        content.showText(c + "");
        height -= 5;
      }
      content.endText();
    }
    stamper.close();
  }
コード例 #18
0
  /** Call to explicitly go to the next page from within a single draw(). */
  public void nextPage() {
    PStyle savedStyle = getStyle();
    g2.dispose();

    try {
      //    writer.setPageEmpty(false);  // maybe useful later
      document.newPage(); // is this bad if no addl pages are made?
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (textMode == SHAPE) {
      g2 = content.createGraphicsShapes(width, height);
    } else if (textMode == MODEL) {
      g2 = content.createGraphics(width, height, mapper);
    }
    style(savedStyle);

    // should there be a beginDraw/endDraw in here?
  }
コード例 #19
0
 public static PdfTemplate createBashingTemplate(
     PdfContentByte directContent, final Color strokeColor) {
   PdfTemplate bashingSlash = directContent.createTemplate(HEALTH_RECT_SIZE, HEALTH_RECT_SIZE);
   bashingSlash.setLineWidth(1f);
   bashingSlash.setColorStroke(strokeColor);
   bashingSlash.moveTo(0, 0);
   bashingSlash.lineTo(HEALTH_RECT_SIZE, HEALTH_RECT_SIZE);
   bashingSlash.stroke();
   return bashingSlash;
 }
コード例 #20
0
  /** @see com.lowagie.toolbox.AbstractTool#execute() */
  public void execute() {
    try {
      if (getValue("odd") == null)
        throw new InstantiationException("You need to choose a sourcefile for the odd pages");
      File odd_file = (File) getValue("odd");
      if (getValue("even") == null)
        throw new InstantiationException("You need to choose a sourcefile for the even pages");
      File even_file = (File) getValue("even");
      if (getValue("destfile") == null)
        throw new InstantiationException("You need to choose a destination file");
      File pdf_file = (File) getValue("destfile");
      RandomAccessFileOrArray odd = new RandomAccessFileOrArray(odd_file.getAbsolutePath());
      RandomAccessFileOrArray even = new RandomAccessFileOrArray(even_file.getAbsolutePath());
      Image img = TiffImage.getTiffImage(odd, 1);
      Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
      document.open();
      PdfContentByte cb = writer.getDirectContent();
      int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even));
      for (int c = 0; c < count; ++c) {
        try {
          Image imgOdd = TiffImage.getTiffImage(odd, c + 1);
          Image imgEven = TiffImage.getTiffImage(even, count - c);
          document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight()));
          document.newPage();
          imgOdd.setAbsolutePosition(0, 0);
          cb.addImage(imgOdd);
          document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight()));
          document.newPage();
          imgEven.setAbsolutePosition(0, 0);
          cb.addImage(imgEven);

        } catch (Exception e) {
          System.out.println("Exception page " + (c + 1) + " " + e.getMessage());
        }
      }
      odd.close();
      even.close();
      document.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #21
0
 public static PdfTemplate createLethalTemplate(
     PdfContentByte directContent, final Color strokeColor) {
   PdfTemplate lethalCross = directContent.createTemplate(HEALTH_RECT_SIZE, HEALTH_RECT_SIZE);
   lethalCross.addTemplate(createBashingTemplate(directContent, strokeColor), 0, 0);
   lethalCross.setLineWidth(1f);
   lethalCross.setColorStroke(strokeColor);
   lethalCross.moveTo(0, HEALTH_RECT_SIZE);
   lethalCross.lineTo(HEALTH_RECT_SIZE, 0);
   lethalCross.stroke();
   return lethalCross;
 }
コード例 #22
0
 public static PdfTemplate createAggravatedTemplate(
     PdfContentByte directContent, final Color strokeColor) {
   PdfTemplate aggravatedStar = directContent.createTemplate(HEALTH_RECT_SIZE, HEALTH_RECT_SIZE);
   aggravatedStar.addTemplate(createLethalTemplate(directContent, strokeColor), 0, 0);
   aggravatedStar.setLineWidth(1f);
   aggravatedStar.setColorStroke(strokeColor);
   aggravatedStar.moveTo(HEALTH_RECT_SIZE / 2f, 0);
   aggravatedStar.lineTo(HEALTH_RECT_SIZE / 2f, HEALTH_RECT_SIZE);
   aggravatedStar.stroke();
   return aggravatedStar;
 }
コード例 #23
0
ファイル: MetaDoPS.java プロジェクト: pinnymz/pdftk_ext
  public void readAll() throws IOException, DocumentException {

    cb.saveState();
    java.awt.Graphics2D g2 = cb.createGraphicsShapes(PageSize.A4.width(), PageSize.A4.height());
    try {
      PAContext context =
          new PAContext(
              (Graphics2D) g2,
              new Dimension((int) PageSize.A4.width(), (int) PageSize.A4.height()));
      context.draw(new BufferedInputStream(in));
      // ( (Graphics2D) backBuffer.getGraphics()).dispose();
      in.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (PainterException ex) {
      ex.printStackTrace();
    }

    cb.restoreState();
  }
コード例 #24
0
  /**
   * This method creat Mark whit proporshin
   *
   * @param content - where we write
   * @param x - lower left x
   * @param y - lower left y
   * @param size - size of mark
   */
  public static void markCircle(PdfContentByte content, int x, int y, int size) {
    // Proportion 1:1:3:1:1
    int sizeStep = size / 7;
    int center = size / 2;
    if (sizeStep < 1) {
      try {
        throw new IllegalArgumentException("Marker must be aliquot 7");
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {

      content.circle(x, y, center);
      content.fill();
      // content.setRGBColorFill(0x00, 0x00, 0x00);
      content.setRGBColorStroke(0xFF, 0xFF, 0xFF);
      content.setLineWidth(sizeStep);
      content.circle(x, y, (float) (center - (sizeStep * 1.5)));

      //            content.setRGBColorFill(0xFF, 0xFF, 0xFF);
      //            content.setLineWidth(10f);
      //            content.circle(350.0f, 300.0f, 50.0f);

      content.fillStroke();
    }
  }
コード例 #25
0
ファイル: SgtUtil.java プロジェクト: BobSimons/erddap
  /**
   * This creates a file to capture the pdf output generated by calls to graphics2D (e.g., use
   * makeMap). This will overwrite an existing file.
   *
   * @param pageSize e.g, PageSize.LETTER or PageSize.LETTER.rotate() (or A4, or, ...)
   * @param width the bounding box width, in 1/144ths of an inch
   * @param height the bounding box height, in 1/144ths of an inch
   * @param outputStream
   * @return an object[] with 0=g2D, 1=document, 2=pdfContentByte, 3=pdfTemplate
   * @throws Exception if trouble
   */
  public static Object[] createPdf(
      com.lowagie.text.Rectangle pageSize, int bbWidth, int bbHeight, OutputStream outputStream)
      throws Exception {
    // currently, this uses itext
    // see the sample program:
    //
    // file://localhost/C:/programs/iText/examples/com/lowagie/examples/directcontent/graphics2D/G2D.java
    // Document.compress = false; //for test purposes only
    Document document = new Document(pageSize);
    document.addCreationDate();
    document.addCreator("gov.noaa.pfel.coastwatch.SgtUtil.createPdf");

    document.setPageSize(pageSize);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();

    // create contentByte and template and Graphics2D objects
    PdfContentByte pdfContentByte = writer.getDirectContent();
    PdfTemplate pdfTemplate = pdfContentByte.createTemplate(bbWidth, bbHeight);
    Graphics2D g2D = pdfTemplate.createGraphics(bbWidth, bbHeight);

    return new Object[] {g2D, document, pdfContentByte, pdfTemplate};
  }
コード例 #26
0
ファイル: JTable2Pdf.java プロジェクト: aristhanemi/git
  private void print() {
    Document document = new Document(PageSize.A4.rotate());
    try {
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("jTable.pdf"));

      document.open();
      PdfContentByte cb = writer.getDirectContent();

      cb.saveState();
      Graphics2D g2 = cb.createGraphicsShapes(500, 500);

      Shape oldClip = g2.getClip();
      g2.clipRect(0, 0, 500, 500);

      table.print(g2);
      g2.setClip(oldClip);

      g2.dispose();
      cb.restoreState();
    } catch (Exception e) {
      System.err.println(e.getMessage());
    }
    document.close();
  }
コード例 #27
0
  /**
   * Método que dibuja los bordes de la página.
   *
   * @param writer Creador de documentos.
   * @param document Documento del informe.
   */
  protected void drawBorders(PdfWriter writer, Document document) {
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();

    // Dibujar el borde de la página
    cb.setColorStroke(BORDER_COLOR);
    cb.setLineWidth(0.5f);
    cb.rectangle(
        document.left(),
        document.bottom(),
        document.right() - document.left(),
        document.top() - document.bottom());
    cb.stroke();

    cb.restoreState();
  }
コード例 #28
0
ファイル: Destinations.java プロジェクト: kjella/iText-4.2.0
  /**
   * Creates a document with some goto actions.
   *
   * @param args no arguments needed
   */
  public static void main(String[] args) {

    System.out.println("Destinations");

    // step 1: creation of a document-object
    Document document = new Document();
    try {

      // step 2:
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Destinations.pdf"));
      // step 3:
      writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
      document.open();
      // step 4: we grab the ContentByte and do some stuff with it
      PdfContentByte cb = writer.getDirectContent();

      // we create a PdfTemplate
      PdfTemplate template = cb.createTemplate(25, 25);

      // we add some crosses to visualize the destinations
      template.moveTo(13, 0);
      template.lineTo(13, 25);
      template.moveTo(0, 13);
      template.lineTo(50, 13);
      template.stroke();

      // we add the template on different positions
      cb.addTemplate(template, 287, 787);
      cb.addTemplate(template, 187, 487);
      cb.addTemplate(template, 487, 287);
      cb.addTemplate(template, 87, 87);

      // we define the destinations
      PdfDestination d1 = new PdfDestination(PdfDestination.XYZ, 300, 800, 0);
      PdfDestination d2 = new PdfDestination(PdfDestination.FITH, 500);
      PdfDestination d3 = new PdfDestination(PdfDestination.FITR, 200, 300, 400, 500);
      PdfDestination d4 = new PdfDestination(PdfDestination.FITBV, 100);
      PdfDestination d5 = new PdfDestination(PdfDestination.FIT);

      // we define the outlines
      PdfOutline out1 = new PdfOutline(cb.getRootOutline(), d1, "root");
      PdfOutline out2 = new PdfOutline(out1, d2, "sub 1");
      new PdfOutline(out1, d3, "sub 2");
      new PdfOutline(out2, d4, "sub 2.1");
      new PdfOutline(out2, d5, "sub 2.2");
    } catch (Exception de) {
      de.printStackTrace();
    }

    // step 5: we close the document
    document.close();
  }
コード例 #29
0
 public void execute(PdfContentByte cb, BaseFont bf) {
   String t = sanitizeText(getText());
   Barcode128 code128 = new Barcode128();
   code128.setGenerateChecksum(true);
   code128.setCode(t);
   if (!isShowText()) {
     code128.setFont(null);
   }
   code128.setBarHeight(getSize());
   Image img = code128.createImageWithBarcode(cb, getColor(), getColor());
   // float w = code128.getBarcodeSize().width() / 2;
   img.setAbsolutePosition(getOffsetX(), getOffsetY());
   img.setRotationDegrees(getDirection());
   try {
     cb.addImage(img);
   } catch (DocumentException e) {
     // Do nothing for the time being...
   }
 }
コード例 #30
0
 /**
  * Writing vertical text.
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) {
   Document document = new Document(PageSize.A4, 50, 50, 50, 50);
   try {
     texts[3] = convertCid(texts[0]);
     texts[4] = convertCid(texts[1]);
     texts[5] = convertCid(texts[2]);
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("vertical.pdf"));
     int idx = 0;
     document.open();
     PdfContentByte cb = writer.getDirectContent();
     for (int j = 0; j < 2; ++j) {
       BaseFont bf = BaseFont.createFont("KozMinPro-Regular", encs[j], false);
       cb.setRGBColorStroke(255, 0, 0);
       cb.setLineWidth(0);
       float x = 400;
       float y = 700;
       float height = 400;
       float leading = 30;
       int maxLines = 6;
       for (int k = 0; k < maxLines; ++k) {
         cb.moveTo(x - k * leading, y);
         cb.lineTo(x - k * leading, y - height);
       }
       cb.rectangle(x, y, -leading * (maxLines - 1), -height);
       cb.stroke();
       int status;
       VerticalText vt = new VerticalText(cb);
       vt.setVerticalLayout(x, y, height, maxLines, leading);
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20)));
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.blue)));
       status = vt.go();
       System.out.println(status);
       vt.setAlignment(Element.ALIGN_RIGHT);
       vt.addText(new Chunk(texts[idx++], new Font(bf, 20, 0, Color.orange)));
       status = vt.go();
       System.out.println(status);
       document.newPage();
     }
     document.close();
   } catch (Exception de) {
     de.printStackTrace();
   }
 }