Example #1
0
  private static void merge(String output, Collection<Path> all) {

    try {
      Document document = new Document();

      PdfCopy copy = new PdfCopy(document, new FileOutputStream(output));
      document.open();

      PdfReader reader;
      int n;

      for (Path pathTemp : all) {

        if (pathTemp.toFile().getAbsolutePath().endsWith(".pdf")) {

          reader = new PdfReader(pathTemp.toFile().getAbsolutePath());

          n = reader.getNumberOfPages();
          for (int page = 0; page < n; ) {
            copy.addPage(copy.getImportedPage(reader, ++page));
          }
          copy.freeReader(reader);
          reader.close();
        }
      }
      document.close();

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Example #2
0
  public static void main(String[] args) {
    try {

      // Step 1: Init document
      Document document = new Document();

      // Step 2: Init pdf file
      String file = "Pdf.pdf"; // Default will 'pdf' project folder
      PdfWriter.getInstance(document, new FileOutputStream(file));

      // Step 3: Open document
      document.open();

      // Step 4: Add connent

      Paragraph paragraph = new Paragraph("This is content");
      document.add(paragraph);

      // ...

      // Step 5: Close document
      document.close();

      System.out.println("OK");

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
Example #3
0
 private void startNewPage() {
   if (document.isOpen()) {
     document.newPage();
   } else {
     document.open();
   }
 }
 /**
  * Converts the given txt file to pdf. It writes the result into the file by the name given in the
  * outputFileName variable.
  *
  * @param inputFileName the name of a text file to convert to PDF
  * @param encoding used by the file
  * @param outputFontName for Polish files recommended is to use "lucon.ttf"
  * @param fontSize the size of font to use in the pdf
  * @param isLandscapeMode if true the pdf pages will be in landscape otherwise they are in
  *     portrait
  * @param outputFileName the name of a pdf file to convert to
  * @throws DocumentException
  * @throws IOException
  */
 public static void convertTextToPDFFile(
     String inputFileName,
     String encoding,
     String outputFontName,
     float fontSize,
     boolean isLandscapeMode,
     String outputFileName)
     throws DocumentException, IOException {
   String fileContent = ReadWriteTextFileWithEncoding.read(inputFileName, encoding);
   //		fileContent = fileContent.replaceAll("\t", tabAsSpaces);
   //	System.out.println("??? czy zawiera ten char ("+newPageChar+") -1 znaczy brak="+
   //		fileContent.indexOf(newPageChar));
   //	System.out.println("fileContent="+fileContent);
   Rectangle pageSize = PageSize.A4;
   if (isLandscapeMode) pageSize = PageSize.A4.rotate();
   Document document = new Document(pageSize);
   // we'll create the file in memory
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   PdfWriter.getInstance(document, baos);
   document.open();
   // stworz czcionke kompatibilna z polskimi literami/kodowaniem
   BaseFont bf = BaseFont.createFont(outputFontName, encoding, BaseFont.EMBEDDED);
   Font font = new Font(bf, fontSize);
   Paragraph par = new Paragraph(fileContent, font);
   document.add(par);
   document.close();
   // let's write the file in memory to a file anyway
   FileOutputStream fos = new FileOutputStream(outputFileName);
   fos.write(baos.toByteArray());
   fos.close();
   System.out.println("Convertion finished, result stored in file '" + outputFileName + "'");
 }
 /**
  * Calculates the maximum font size, which will fits all characters of the given fileContent into
  * the document's page width.
  *
  * @param document where the text will be inputed.
  * @param fileContent the content of the file the will be written.
  * @param fontName the name of the font which will be used while writing into a file.
  * @param encoding the encoding which will be used while writing into a file.
  * @return the max size of the font that will fit the string into the given document's page width.
  * @throws IOException
  * @throws DocumentException
  */
 public static float calculateFontSizeFittingAllStringIntoPageWidth(
     Document document, String fileContent, String fontName, String encoding)
     throws IOException, DocumentException {
   String longestLineOfParagraph = "";
   String newLineMarker = System.getProperty("line.separator");
   String[] lineArray = fileContent.split(newLineMarker);
   //	System.out.println("lineArray.length="+lineArray.length);
   for (int i = 0; i < lineArray.length; i++) {
     String line = lineArray[i];
     if (longestLineOfParagraph.length() < line.length()) longestLineOfParagraph = line;
   }
   // Round margins' size up...
   int marignLeft = (int) (document.leftMargin() + 1);
   int marginRight = (int) (document.rightMargin() + 1);
   // round page width down...
   int pageWidth = (int) document.getPageSize().getWidth();
   // ...to make sure we have correct max space for text.
   int maxSpaceForText = pageWidth - marignLeft - marginRight;
   System.out.println(
       "marignLeft="
           + marignLeft
           + ";  marginRight="
           + marginRight
           + ";  pageWidth="
           + pageWidth
           + ";  maxSpaceForText="
           + maxSpaceForText);
   float fontSize = 12.0f;
   BaseFont bf = BaseFont.createFont(fontName, encoding, BaseFont.EMBEDDED);
   float textWidthForFontSize = bf.getWidthPointKerned(longestLineOfParagraph, fontSize);
   float requiredFontSize = (fontSize * maxSpaceForText) / textWidthForFontSize;
   return requiredFontSize;
 }
  public static void main(String[] args) throws IOException, DocumentException {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontFamily = ge.getAvailableFontFamilyNames();
    PrintStream out1 = new PrintStream(new FileOutputStream(RESULT1));
    for (int i = 0; i < fontFamily.length; i++) {
      out1.println(fontFamily[i]);
    }
    out1.flush();
    out1.close();

    DefaultFontMapper mapper = new DefaultFontMapper();
    mapper.insertDirectory("c:/windows/fonts/");
    PrintStream out2 = new PrintStream(new FileOutputStream(RESULT2));
    for (Entry<String, BaseFontParameters> entry : mapper.getMapper().entrySet()) {
      out2.println(String.format("%s: %s", entry.getKey(), entry.getValue().fontName));
    }
    out2.flush();
    out2.close();

    float width = 150;
    float height = 150;
    Document document = new Document(new Rectangle(width, height));
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT3));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Graphics2D g2d = cb.createGraphics(width, height, mapper);
    for (int i = 0; i < FONTS.length; ) {
      g2d.setFont(FONTS[i++]);
      g2d.drawString("Hello world", 5, 24 * i);
    }
    g2d.dispose();
    document.close();
  }
 public static void main(String[] args) throws IOException, DocumentException {
   Document document = new Document();
   PdfWriter.getInstance(document, new FileOutputStream("results/simple_rowspan_colspan.pdf"));
   document.open();
   PdfPTable table = new PdfPTable(5);
   table.setWidths(new int[] {1, 2, 2, 2, 1});
   PdfPCell cell;
   cell = new PdfPCell(new Phrase("S/N"));
   cell.setRowspan(2);
   table.addCell(cell);
   cell = new PdfPCell(new Phrase("Name"));
   cell.setColspan(3);
   table.addCell(cell);
   cell = new PdfPCell(new Phrase("Age"));
   cell.setRowspan(2);
   table.addCell(cell);
   table.addCell("SURNAME");
   table.addCell("FIRST NAME");
   table.addCell("MIDDLE NAME");
   table.addCell("1");
   table.addCell("James");
   table.addCell("Fish");
   table.addCell("Stone");
   table.addCell("17");
   document.add(table);
   document.close();
 }
Example #8
0
 /**
  * Creates a PDF document.
  *
  * @param filename the path to the new PDF document
  * @throws DocumentException
  * @throws IOException
  */
 public void createPdf(String filename) throws IOException, DocumentException {
   // step 1
   Document document = new Document(new Rectangle(360, 360));
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
   // step 3
   document.open();
   writer.addJavaScript(Utilities.readFileToString(RESOURCE));
   // step 4
   // add the keys for the digits
   for (int i = 0; i < 10; i++) {
     addPushButton(writer, digits[i], String.valueOf(i), "this.augment(" + i + ")");
   }
   // add the keys for the operators
   addPushButton(writer, plus, "+", "this.register('+')");
   addPushButton(writer, minus, "-", "this.register('-')");
   addPushButton(writer, mult, "x", "this.register('*')");
   addPushButton(writer, div, ":", "this.register('/')");
   addPushButton(writer, equals, "=", "this.calculateResult()");
   // add the other keys
   addPushButton(writer, clearEntry, "CE", "this.reset(false)");
   addPushButton(writer, clear, "C", "this.reset(true)");
   addTextField(writer, result, "result");
   addTextField(writer, move, "move");
   // step 5
   document.close();
 }
Example #9
0
 private void exportGraphToPdf(mxGraph graph, String filename) {
   Rectangle bounds =
       new Rectangle(trackScheme.getGUI().graphComponent.getViewport().getViewSize());
   // step 1
   com.itextpdf.text.Rectangle pageSize =
       new com.itextpdf.text.Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
   com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize);
   // step 2
   PdfWriter writer = null;
   Graphics2D g2 = null;
   try {
     writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
     // step 3
     document.open();
     // step 4
     PdfContentByte canvas = writer.getDirectContent();
     g2 = canvas.createGraphics(pageSize.getWidth(), pageSize.getHeight());
     trackScheme.getGUI().graphComponent.getViewport().paintComponents(g2);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (DocumentException e) {
     e.printStackTrace();
   } finally {
     g2.dispose();
     document.close();
   }
 }
Example #10
0
  public void setHeader(Document document, String clientName)
      throws DocumentException, IOException {

    LineSeparator line = new LineSeparator(1, 80, null, Element.ALIGN_CENTER, -5);

    Image img = Image.getInstance(getClass().getResource("img/LISLogo.png"));
    // Image img = Image.getInstance("img/LISLogo.png");
    img.scaleAbsoluteHeight(80);
    img.scaleAbsoluteWidth(200);
    img.setAlignment(Element.ALIGN_CENTER);

    Paragraph clientNameParagraph = new Paragraph();
    clientNameParagraph.setAlignment(Element.ALIGN_CENTER);
    clientNameParagraph.add(clientName);
    clientNameParagraph.setSpacingAfter(12);

    Paragraph investmentRecommendations = new Paragraph("Your Legacy Investment Income Portfolio");
    investmentRecommendations.setAlignment(Element.ALIGN_CENTER);
    investmentRecommendations.add(line);
    investmentRecommendations.setSpacingAfter(4);

    document.add(clientNameParagraph);
    document.add(investmentRecommendations);
    document.add(img);
  }
 private void addMetaData(Document document) {
   document.addTitle("My first PDF");
   document.addSubject("Using iText");
   document.addKeywords("Java, PDF, iText");
   document.addAuthor("Lars Vogel");
   document.addCreator("Lars Vogel");
 }
  /**
   * Creates a PDF document.
   *
   * @param filename the path to the new PDF document
   * @throws DocumentException
   * @throws IOException
   */
  public void createPdf(String filename) throws IOException, DocumentException {
    // step 1
    Rectangle rect = new Rectangle(-595, -842, 595, 842);
    Document document = new Document(rect);
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    // draw the coordinate system
    PdfContentByte canvas = writer.getDirectContent();
    canvas.moveTo(-595, 0);
    canvas.lineTo(595, 0);
    canvas.moveTo(0, -842);
    canvas.lineTo(0, 842);
    canvas.stroke();

    // read the PDF with the logo
    PdfReader reader = new PdfReader(RESOURCE);
    PdfTemplate template = writer.getImportedPage(reader, 1);
    // add it at different positions using different transformations
    canvas.addTemplate(template, 0, 0);
    canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -595, 0);
    canvas.addTemplate(template, 0.5f, 0, 0, 0.5f, -297.5f, 297.5f);
    canvas.addTemplate(template, 1, 0, 0.4f, 1, -750, -650);
    canvas.addTemplate(template, 0, -1, -1, 0, 650, 0);
    canvas.addTemplate(template, 0, -0.2f, -0.5f, 0, 350, 0);
    // step 5
    document.close();
    reader.close();
  }
Example #13
0
  /** Generates a PDF with the list of registered members in the event. */
  public void print() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "inline=filename=file.pdf");

    try {
      Document document = new Document();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, baos);
      document.open();

      EventAttendeeReport eventAttendeeReport = new EventAttendeeReport(document);
      eventAttendeeReport.printReport(this.attendees);

      document.close();

      response.getOutputStream().write(baos.toByteArray());
      response.getOutputStream().flush();
      response.getOutputStream().close();
      context.responseComplete();
    } catch (IOException | DocumentException e) {
      LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
  }
  private void addProductDetails(Document document) throws BadElementException, DocumentException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 5);
    document.add(preface);

    PdfPTable table = new PdfPTable(3);

    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    PdfPCell c1 = new PdfPCell(new Phrase("Product ID"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    PdfPCell c2 = new PdfPCell(new Phrase("Current Stock"));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c2);

    PdfPCell c3 = new PdfPCell(new Phrase("Minimum Stock"));
    c3.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c3);

    table.setHeaderRows(1);

    ArrayList<ArrayList<String>> products = rprtDBAccess.getLowStockedProducts();

    for (int i = 0; i < products.size(); i++) {
      ArrayList<String> product = products.get(i);
      table.addCell(product.get(0)); // product id
      table.addCell(product.get(1)); // currentstock
      table.addCell(product.get(2)); // minimumstock

      table.completeRow();
    }
    document.add(table);
  }
Example #15
0
  public static void main(String[] args) throws FileNotFoundException, DocumentException {
    Document document = new Document();
    @SuppressWarnings("unused")
    PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
    document.open();

    Paragraph paragraph1 = new Paragraph("This is Paragraph 1");
    Paragraph paragraph2 = new Paragraph("This is Paragraph 2");
    paragraph1.setIndentationLeft(80);
    paragraph1.setIndentationRight(80);
    paragraph1.setAlignment(Element.ALIGN_CENTER);
    paragraph1.setSpacingAfter(15);
    paragraph2.setSpacingBefore(15);
    paragraph2.setAlignment(Element.ALIGN_LEFT);
    Phrase phrase = new Phrase("This is a large sentence.");
    for (int count = 0; count < 10; count++) {
      paragraph1.add(phrase);
      paragraph2.add(phrase);
    }

    document.add(paragraph1);
    document.add(paragraph2);

    document.close();
  }
 private static void concatPDFs(List<String> pdfs, OutputStream outputStream, String tempDiv) {
   ByteArrayOutputStream byteStream = null;
   Document document = new Document();
   try {
     PdfCopy copy = new PdfCopy(document, outputStream);
     document.open();
     for (String pdf : pdfs) {
       String fileLocation = tempDiv + pdf;
       InputStream templateIs = new FileInputStream(fileLocation);
       PdfReader reader = new PdfReader(templateIs);
       byteStream = new ByteArrayOutputStream();
       PdfStamper stamper = new PdfStamper(reader, byteStream);
       stamper.setFreeTextFlattening(true);
       stamper.setFormFlattening(true);
       stamper.close();
       PdfReader pdfReader = new PdfReader(byteStream.toByteArray());
       for (int page = 0; page < pdfReader.getNumberOfPages(); ) {
         copy.addPage(copy.getImportedPage(pdfReader, ++page));
       }
       pdfReader.close();
       reader.close();
     }
     document.close();
     copy.close();
   } catch (Exception e) {
     logger.error(e, e);
   } finally {
     if (document.isOpen()) document.close();
     try {
       if (outputStream != null) outputStream.close();
     } catch (IOException ioe) {
       logger.error(ioe, ioe);
     }
   }
 }
Example #17
0
  public static void main(String[] args) {
    Document document = new Document();
    try {
      PdfWriter.getInstance(document, new FileOutputStream("ImageRotation.pdf"));
      document.open();

      //
      // Rotate image in radian using the setRotation method.
      //
      String filename = "other-sample/src/main/resources/java.gif";
      Image image = Image.getInstance(filename);
      image.setRotation(90f);
      document.add(image);

      //
      // Rotate image in degree using the setRotationDegree method
      //
      String url = "http://localhost/xampp/img/xampp-logo-new.gif";
      image = Image.getInstance(url);
      image.setRotationDegrees(90);
      document.add(image);
    } catch (DocumentException | IOException e) {
      e.printStackTrace();
    } finally {
      document.close();
    }
  }
Example #18
0
 public Document createdocument(String filename) throws FileNotFoundException, DocumentException {
   Rectangle pagesize = new Rectangle(1650f, 800f);
   Document document = new Document(pagesize);
   PdfWriter.getInstance(document, new FileOutputStream(filename));
   document.open();
   return document;
 }
 private void addMetaData(Document document) {
   String title = mContext.getString(R.string.brew_shop_recipe_colon) + " " + mRecipe.getName();
   String author = mContext.getString(R.string.brew_shop);
   document.addTitle(title);
   document.addSubject(title);
   document.addAuthor(author);
   document.addCreator(author);
 }
 private void addHeader(Document document, Examination examination) throws DocumentException {
   Paragraph p;
   p = new Paragraph("SZÁMLA", headerFont);
   document.add(p);
   p = new Paragraph("Számlaszám: " + examination.getInvoice().getInvoiceId(), boldDataFont);
   p.setAlignment(Element.ALIGN_RIGHT);
   addEmptyLine(p, 2);
   document.add(p);
 }
  public static ByteArrayOutputStream requestsToPdf(
      String globalTitle, Date generationDate, ScrambleRequest[] scrambleRequests, String password)
      throws DocumentException, IOException {
    Document doc = new Document();
    ByteArrayOutputStream totalPdfOutput = new ByteArrayOutputStream();
    PdfSmartCopy totalPdfWriter = new PdfSmartCopy(doc, totalPdfOutput);
    if (password != null) {
      totalPdfWriter.setEncryption(
          password.getBytes(),
          password.getBytes(),
          PdfWriter.ALLOW_PRINTING,
          PdfWriter.STANDARD_ENCRYPTION_128);
    }

    doc.open();

    PdfContentByte cb = totalPdfWriter.getDirectContent();
    PdfOutline root = cb.getRootOutline();

    HashMap<String, PdfOutline> outlineByPuzzle = new HashMap<String, PdfOutline>();
    boolean expandPuzzleLinks = false;

    int pages = 1;
    for (int i = 0; i < scrambleRequests.length; i++) {
      ScrambleRequest scrambleRequest = scrambleRequests[i];

      String shortName = scrambleRequest.scrambler.getShortName();

      PdfOutline puzzleLink = outlineByPuzzle.get(shortName);
      if (puzzleLink == null) {
        PdfDestination d = new PdfDestination(PdfDestination.FIT);
        puzzleLink =
            new PdfOutline(
                root,
                PdfAction.gotoLocalPage(pages, d, totalPdfWriter),
                scrambleRequest.scrambler.getLongName(),
                expandPuzzleLinks);
        outlineByPuzzle.put(shortName, puzzleLink);
      }

      PdfDestination d = new PdfDestination(PdfDestination.FIT);
      new PdfOutline(
          puzzleLink, PdfAction.gotoLocalPage(pages, d, totalPdfWriter), scrambleRequest.title);

      PdfReader pdfReader = createPdf(globalTitle, generationDate, scrambleRequest);
      for (int j = 0; j < scrambleRequest.copies; j++) {
        for (int pageN = 1; pageN <= pdfReader.getNumberOfPages(); pageN++) {
          PdfImportedPage page = totalPdfWriter.getImportedPage(pdfReader, pageN);
          totalPdfWriter.addPage(page);
          pages++;
        }
      }
    }

    doc.close();
    return totalPdfOutput;
  }
Example #22
0
  public void print(String filename) throws IOException, DocumentException {
    EventTree tree = app.getTimelines().getCurrentTree();
    if (tree == null || tree.isEmpty()) return;

    ComplexEvent parent = tree.getTopSelectionParent();
    if (parent == null) return;

    // Instantiation of document object
    Document document = new Document(PageSize.A4, 50, 50, 50, 50);

    // Creation of PdfWriter object
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();

    // Creation of table
    Paragraph title =
        new Paragraph(
            "A sample output from Zeitline:",
            FontFactory.getFont(FontFactory.TIMES_BOLD, 14, BaseColor.BLUE));
    title.setSpacingAfter(20);
    document.add(title);

    // Setting width rations
    PdfPTable table = new PdfPTable(3);
    float[] tableWidth = {(float) 0.2, (float) 0.12, (float) 0.68};
    table.setWidths(tableWidth);

    // Setting the header
    java.util.List<PdfPCell> headerCells =
        asList(getHeaderCell("Date"), getHeaderCell("MACB"), getHeaderCell("Short Description"));

    for (PdfPCell cell : headerCells) table.addCell(cell);

    // Setting the body
    int max = parent.countChildren();
    for (int i = 0; i < max; i++) {
      AbstractTimeEvent entry = parent.getEventByIndex(i);
      table.addCell(getBodyCell(entry.getStartTime().toString()));

      String name = entry.getName();
      if (name != null && name.length() > 5) {
        String macb = name.substring(0, 4);
        String desc = name.substring(5);

        table.addCell(getBodyCell(macb));
        table.addCell(getBodyCell(desc));
      } else {
        table.addCell("");
        table.addCell("");
      }
    }
    document.add(table);

    // Closure
    document.close();
    writer.close();
  }
 private void addNotes(Document document) throws DocumentException {
   if (!mRecipe.getNotes().equals("")) {
     document.add(new Paragraph(mContext.getString(R.string.notes), HEADER_FONT));
     addLineSeparator(document);
     Paragraph notesPara = new Paragraph(mRecipe.getNotes(), NORMAL_FONT);
     notesPara.setLeading(NORMAL_POINT);
     document.add(notesPara);
   }
 }
Example #24
0
  public void pintaCodigoBarras() {

    Image imageLogo;
    Image imageBarc = null;
    String imageUrl;

    Font fuente = new Font(FontFamily.HELVETICA, 8, Font.NORMAL, new BaseColor(64, 64, 64));
    BaseColor bkcolor = new BaseColor(255, 255, 255);

    try {

      PdfPTable table = new PdfPTable(new float[] {1, 1, 1, 1, 1});
      // table.setTotalWidth(900);
      table.getDefaultCell().setBorder(0);
      //	imageUrl = PropiedadesJLet.getInstance().getProperty("path.img.logos") +
      // "logo_recibos.png";

      // imageLogo = Image.getInstance(imageUrl);

      int yinic = 805;
      int xinic = 0;

      int posicion = 0; // posicion donde comenzara a imprimir

      // for (int i = 0; i < listcode.size(); i++){

      String codeunic = codvalue;

      // System.out.println(codeunic.substring(0,5) +"-"+ codeunic.substring(6,7));

      imageBarc = getBarcode(documento, writer, codeunic);

      PdfPTable tablein = new PdfPTable(new float[] {1f, 3f, 1f});

      tablein.getDefaultCell().setBorder(0);
      tablein.setTotalWidth(documento.getPageSize().getWidth());

      tablein.addCell(FRAparen.getCelda(" ", fuente, bkcolor, "center")).setBorder(0);
      // tablein.addCell(imageLogo);
      tablein.addCell(FRAparen.getCelda(" ", fuente, bkcolor, "center")).setBorder(0);

      tablein.addCell(FRAparen.getCelda(" ", fuente, bkcolor, "center")).setBorder(0);
      tablein.addCell(imageBarc);
      tablein.addCell(FRAparen.getCelda(" ", fuente, bkcolor, "center")).setBorder(0);

      table.addCell(tablein);

      imageBarc.scaleAbsolute(anchcdba, altocdba);
      imageBarc.setAbsolutePosition(xposicio, yposicio);

      documento.add(imageBarc);

    } catch (Exception e) {

    }
  }
 public void createPdf2(String src) throws IOException, DocumentException {
   // second document (with a link to the first one)
   Document document2 = new Document();
   PdfWriter.getInstance(document2, new FileOutputStream(src));
   document2.open();
   Chunk chunk = new Chunk("Link");
   chunk.setAction(new PdfAction("subdir/abc2.pdf", 6));
   document2.add(chunk);
   document2.close();
 }
Example #26
0
  public static void PDF(String DirPath, String FileName, String Text, Font fonts)
      throws FileNotFoundException, DocumentException {
    FileOutputStream Dir = new FileOutputStream(DirPath + FileName);
    Document doc = new Document();
    PdfWriter.getInstance(doc, Dir);

    doc.open();
    doc.add(new Paragraph(Text, fonts));
    doc.close();
  }
  @Override
  public byte[] buildReportFromFiche(Fiche fiche) throws DocumentException {

    logger.debug("Début méthode exportation PDF");

    if (fiche.getAdresse() == null) {
      throw new BusinessException(
          "Impossible d'imprimer cette fiche : L'adresse n'est pas remplie.");
    }

    ByteArrayOutputStream bstream = new ByteArrayOutputStream();

    logger.debug("Génération du PDF");

    Document document = new Document();
    PdfWriter.getInstance(document, bstream);
    document = buildMetadata(document, fiche);

    document.open();
    document.add(buildHeader(fiche));
    document.add(buildInfos(fiche));
    document.add(buildSaisine(fiche));
    document.add(buildExpose(fiche));
    document.add(buildPersonnes(fiche));
    document.add(buildProcedures(fiche));

    document.close();

    logger.debug("Fin de génération");

    return bstream.toByteArray();
  }
  @Override
  protected void buildPdfDocument(
      Map<String, Object> model,
      Document doc,
      PdfWriter writer,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // TODO Auto-generated method stub

    @SuppressWarnings("unchecked")
    ArrayList<ctUsuario> listaUsuario = (ArrayList<ctUsuario>) model.get("listaUsuario");
    // grupo = (String)model.get("grupo");

    PdfPTable tablaPDF = new PdfPTable(11); // 11 columns.
    Font fuenteTabla = new Font(Font.FontFamily.UNDEFINED, 12, Font.BOLD);
    Font fuenteCelda = new Font(Font.FontFamily.UNDEFINED, 11);

    tablaPDF.addCell(new Phrase("Nombre", fuenteTabla));
    tablaPDF.addCell(new Phrase("Apellido", fuenteTabla));
    tablaPDF.addCell(new Phrase("Fecha De Nacimiento", fuenteTabla));
    tablaPDF.addCell(new Phrase("Calle", fuenteTabla));
    tablaPDF.addCell(new Phrase("Num. Ext", fuenteTabla));
    tablaPDF.addCell(new Phrase("Num. Int", fuenteTabla));
    tablaPDF.addCell(new Phrase("Colonia", fuenteTabla));
    tablaPDF.addCell(new Phrase("CP", fuenteTabla));
    tablaPDF.addCell(new Phrase("Municipio", fuenteTabla));
    tablaPDF.addCell(new Phrase("Estado", fuenteTabla));
    tablaPDF.addCell(new Phrase("Telefono", fuenteTabla));

    for (ctUsuario ctUsuario : listaUsuario) {
      tablaPDF.addCell(new Phrase(ctUsuario.getcNombre(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcApellidos(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getDtFechaNac(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcCalle(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcNumExterior(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcNumInterior(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcColonia(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcCP(), fuenteCelda));
      // tablaPDF.addCell(new Phrase(ctUsuario.getcMunicipio(), fuenteCelda));
      tablaPDF.addCell(new Phrase(ctUsuario.getcEstado(), fuenteCelda));
      // tablaPDF.addCell(new Phrase(ctUsuario.getcTel(), fuenteCelda));
    }

    tablaPDF.setWidthPercentage(100);
    Rectangle rect = new Rectangle(60, 30, 600, 800);
    writer.setBoxSize("art", rect);
    HeaderFooterPageEvent event = new HeaderFooterPageEvent();
    writer.setPageEvent(event);
    doc.setPageSize(PageSize.A4.rotate());
    doc.open();
    doc.add(tablaPDF);
    doc.close();
    pages = 0;
  }
 /**
  * Creates a PDF file: hello_mirrored_margins.pdf
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) throws DocumentException, IOException {
   // step 1
   Document document = new Document();
   // step 2
   PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // setting page size, margins and mirrered margins
   document.setPageSize(PageSize.A5);
   document.setMargins(36, 72, 108, 180);
   document.setMarginMirroringTopBottom(true);
   // step 3
   document.open();
   // step 4
   document.add(
       new Paragraph(
           "The left margin of this odd page is 36pt (0.5 inch); "
               + "the right margin 72pt (1 inch); "
               + "the top margin 108pt (1.5 inch); "
               + "the bottom margin 180pt (2.5 inch)."));
   Paragraph paragraph = new Paragraph();
   paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
   for (int i = 0; i < 20; i++) {
     paragraph.add(
         "Hello World! Hello People! " + "Hello Sky! Hello Sun! Hello Moon! Hello Stars!");
   }
   document.add(paragraph);
   document.add(new Paragraph("The top margin 180pt (2.5 inch)."));
   // step 5
   document.close();
 }
Example #30
0
  /**
   * @param file
   * @param txId
   * @throws DocumentException
   * @throws IOException
   */
  public void generatePdf(String file, ArrayList<String> docList)
      throws DocumentException, IOException {
    //  getReqdInfo(txId);
    document = new Document(PageSize.A4, 50, 50, 100, 650);
    writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    writer.setPageEvent(agreementPdf);
    document.open();
    getTransactionHeader(docList);

    document.close();
  }