Пример #1
0
  private static void booklet(String input) throws Exception {
    String output = input.replace(".pdf", "-booklet.pdf");
    PdfReader reader = new PdfReader(input);
    int n = reader.getNumberOfPages();
    Rectangle pageSize = reader.getPageSize(1);

    System.out.println("Input page size: " + pageSize);
    Document doc = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output));
    doc.open();
    splitLine(doc, writer);
    int[] pages = new int[(n + 3) / 4 * 4];
    int x = 1, y = pages.length;
    for (int i = 0; i < pages.length; ) {
      pages[i++] = y--;
      pages[i++] = x++;
      pages[i++] = x++;
      pages[i++] = y--;
    }
    PdfContentByte cb = writer.getDirectContent();
    float bottom = (doc.top() - pageSize.getHeight()) / 2 + kOffset;
    float left = doc.right() / 2 - (pageSize.getWidth() + kTextWidth) / 2 - kMargin;
    float right = doc.right() / 2 - (pageSize.getWidth() - kTextWidth) / 2 + kMargin;

    for (int i = 0; i < pages.length; ) {
      PdfImportedPage page = getPage(writer, reader, pages[i++]);
      if (page != null) cb.addTemplate(page, left, bottom);

      page = getPage(writer, reader, pages[i++]);
      if (page != null) cb.addTemplate(page, right, bottom);

      doc.newPage();
    }
    doc.close();
  }
Пример #2
0
 /**
  * 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 + "'");
 }
  @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;
  }
Пример #4
0
 /**
  * Creates a PDF document.
  *
  * @param filename the path to the new PDF document
  * @param locale Locale in case you want to create a Calendar in another language
  * @param year the year for which you want to make a calendar
  * @throws DocumentException
  * @throws IOException
  */
 public void createPdf(String filename, Locale locale, int year)
     throws IOException, DocumentException {
   // step 1
   Document document = new Document(PageSize.A4.rotate());
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
   // step 3
   document.open();
   // step 4
   PdfPTable table;
   Calendar calendar;
   PdfContentByte canvas = writer.getDirectContent();
   // Loop over the months
   for (int month = 0; month < 12; month++) {
     calendar = new GregorianCalendar(year, month, 1);
     // draw the background
     drawImageAndText(canvas, calendar);
     // create a table with 7 columns
     table = new PdfPTable(7);
     table.setTableEvent(tableBackground);
     table.setTotalWidth(504);
     // add the name of the month
     table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
     table.getDefaultCell().setCellEvent(whiteRectangle);
     table.addCell(getMonthCell(calendar, locale));
     int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
     int day = 1;
     int position = 2;
     // add empty cells
     while (position != calendar.get(Calendar.DAY_OF_WEEK)) {
       position = (position % 7) + 1;
       table.addCell("");
     }
     // add cells for each day
     while (day <= daysInMonth) {
       calendar = new GregorianCalendar(year, month, day++);
       table.addCell(getDayCell(calendar, locale));
     }
     // complete the table
     table.completeRow();
     // write the table to an absolute position
     table.writeSelectedRows(0, -1, 169, table.getTotalHeight() + 20, canvas);
     document.newPage();
   }
   // step 5
   document.close();
 }
 @Override
 public void imprimerBsp(Long idBsp, OutputStream stream) throws ServiceException {
   try {
     Document doc = new Document();
     PdfWriter.getInstance(doc, stream);
     doc.setPageSize(PageSize.A4.rotate());
     doc.open();
     Util.produceHeader(doc);
     BonSortie bs = bonSortieDao.findById(idBsp);
     produceBspTable(bs, doc);
     doc.close();
   } catch (DocumentException ex) {
     Logger.getLogger(OrdreSortieServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
   } catch (Exception ex) {
     Logger.getLogger(OrdreSortieServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Пример #6
0
 public void actionPerformed(ActionEvent e) {
   String verifyResult = verifyInputFields();
   if (verifyResult.equals("")) {
     // do conversion of txt file to pdf
     String inputFileName = fileSelectionPanel.getInputFileName();
     String outputFileName = fileSelectionPanel.getOutputFileName();
     String encoding = (String) encodingCB.getSelectedItem();
     String outputFontName = (String) fontCB.getSelectedItem();
     boolean isLandscapeMode = landscapeRB.isSelected();
     float fontSize = -1.0f;
     if (fitTextToWidthRB.isSelected())
       try {
         Rectangle pageSize = PageSize.A4;
         if (isLandscapeMode) pageSize = PageSize.A4.rotate();
         Document document = new Document(pageSize);
         String fileContent = ReadWriteTextFileWithEncoding.read(inputFileName, encoding);
         fontSize =
             calculateFontSizeFittingAllStringIntoPageWidth(
                 document, fileContent, outputFontName, encoding);
       } catch (IOException ex) {
         Logger.getLogger(CommonPanel.class.getName()).log(Level.SEVERE, null, ex);
       } catch (DocumentException ex) {
         Logger.getLogger(CommonPanel.class.getName()).log(Level.SEVERE, null, ex);
       }
     else fontSize = Float.parseFloat(fontSizeTF.getText());
     try {
       convertTextToPDFFile(
           inputFileName,
           encoding,
           outputFontName,
           fontSize,
           isLandscapeMode,
           outputFileName);
     } catch (DocumentException ex) {
       Logger.getLogger(CommonPanel.class.getName()).log(Level.SEVERE, null, ex);
     } catch (IOException ex) {
       Logger.getLogger(CommonPanel.class.getName()).log(Level.SEVERE, null, ex);
     }
   } else
     JOptionPane.showMessageDialog(
         ownerFrame,
         verifyResult,
         "Cannot convert, becauses:",
         JOptionPane.INFORMATION_MESSAGE);
 }
  @Override
  public byte[] buildReportFromFiches(List<Fiche> fiches, Map<String, String> searchParams) {

    logger.debug("Début exportation rapport Fiche Evenementielle");

    if (fiches.isEmpty()) {
      throw new BusinessException("Aucune fiche à imprimer.");
    }

    ByteArrayOutputStream bstream = new ByteArrayOutputStream();

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

    try {
      String date = new DateTime().toString("dd/MM/YYYY HH:mm");
      Document document = new Document(PageSize.A4.rotate());
      PdfWriter writer = PdfWriter.getInstance(document, bstream);
      FicheEventReportPageTemplate event = new FicheEventReportPageTemplate();
      event.setFooter(date);
      writer.setPageEvent(event);
      document = buildMetadata(document, date);

      document.open();
      document.add(buildHeader(date));
      document.add(buildSearchParams(searchParams));
      document.add(buildTable(fiches));

      document.close();

    } catch (DocumentException | IOException ex) {
      logger.error(
          "Une erreur est survenue lors de l'impression du rapport Fiche Evenementielle", ex);
      throw new BusinessException(
          "Une erreur est survenue lors de l'impression du rapport. Veuillez consulter votre administrateur.",
          ex);
    }

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

    return bstream.toByteArray();
  }
 /**
  * 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(PageSize.A4.rotate());
   // step 2
   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
   // step 3
   document.open();
   // step 4
   PdfContentByte over = writer.getDirectContent();
   PdfContentByte under = writer.getDirectContentUnder();
   try {
     DatabaseConnection connection = new HsqldbConnection("filmfestival");
     locations = PojoFactory.getLocations(connection);
     List<Date> days = PojoFactory.getDays(connection);
     List<Screening> screenings;
     int d = 1;
     for (Date day : days) {
       drawTimeTable(under);
       drawTimeSlots(over);
       drawInfo(over);
       drawDateInfo(day, d++, over);
       screenings = PojoFactory.getScreenings(connection, day);
       for (Screening screening : screenings) {
         drawBlock(screening, under, over);
         drawMovieInfo(screening, over);
       }
       document.newPage();
     }
     connection.close();
   } catch (SQLException sqle) {
     sqle.printStackTrace();
     document.add(new Paragraph("Database error: " + sqle.getMessage()));
   }
   // step 5
   document.close();
 }
Пример #9
0
  public static void createPdf2(
      List<Participant> participants,
      boolean exportName,
      boolean exportGroup,
      boolean exportRenseignement,
      OutputStream out)
      throws IOException, DocumentException {
    Document document = new Document(PageSize.A4.rotate());
    // document.setMargins(0,0,0,0);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    float documentTop = document.top();
    float documentBottom = document.bottom();
    float documentHeight = documentTop - documentBottom;
    float left = document.left();
    float right = document.right();
    float width = right - left;

    cb.rectangle(left, documentBottom, width, documentHeight);
    cb.stroke();

    float nameHeightPercent = 0.35f;
    float groupHeightPercent = 0.25f;

    float nameTop = documentTop;
    float nameBottom = nameTop;
    if (exportName) {
      nameBottom = nameTop - (documentHeight * nameHeightPercent);
    }
    float groupeTop = nameBottom;
    float groupeBottom = nameBottom;
    if (exportGroup) {
      groupeBottom = groupeTop - (documentHeight * groupHeightPercent);
    }
    float barcodeTop = groupeBottom;
    float barcodeBottom = documentBottom;

    ColumnText columnText;

    for (Participant participant : participants) {

      float nameFontSize = 65f;
      float groupFontSize = 45f;
      float renseignementFontSize = 35f;

      if (exportName) {
        columnText = new ColumnText(cb);

        columnText.setSimpleColumn(left, nameTop, right, nameBottom);
        // cb.rectangle(left, nameBottom, width, (nameTop - nameBottom));
        // cb.stroke();

        columnText.setExtraParagraphSpace(0f);
        columnText.setAdjustFirstLine(false);
        columnText.setIndent(0);

        String txt = participant.getNom().toUpperCase() + " " + participant.getPrenom();

        float previousPos = columnText.getYLine();
        columnText.setText(null);
        columnText.addElement(createCleanParagraph(txt, nameFontSize, true));
        while (ColumnText.hasMoreText(columnText.go(true))) {
          nameFontSize = nameFontSize - 0.5f;
          columnText.setText(null);
          columnText.addElement(createCleanParagraph(txt, nameFontSize, true));
          columnText.setYLine(previousPos);
        }

        columnText.setText(null);
        columnText.addElement(createCleanParagraph(txt, nameFontSize, true));
        columnText.setYLine(previousPos);
        columnText.go(false);
      }

      if (exportGroup) {
        columnText = new ColumnText(cb);

        columnText.setSimpleColumn(document.left(), groupeTop, document.right(), groupeBottom);
        float groupeHeight = groupeTop - groupeBottom;
        // cb.rectangle(document.left(), groupeTop - groupeHeight, document.right() -
        // document.left(), groupeHeight);
        // cb.stroke();

        columnText.setExtraParagraphSpace(0f);
        columnText.setAdjustFirstLine(false);
        columnText.setIndent(0);
        columnText.setFollowingIndent(0);

        String txt1 = participant.getGroupe();
        String txt2 = exportRenseignement ? participant.getRenseignements() : null;

        float previousPos = columnText.getYLine();
        columnText.setText(null);
        // columnText.addElement(createCleanParagraph(txt1,groupFontSize,true,txt2,renseignementFontSize,false));
        columnText.addElement(createCleanParagraph(txt1, groupFontSize, true));
        columnText.addElement(createCleanParagraph(txt2, renseignementFontSize, false));
        while (ColumnText.hasMoreText(columnText.go(true))) {
          groupFontSize = groupFontSize - 0.5f;
          renseignementFontSize = renseignementFontSize - 0.5f;
          columnText.setText(null);
          // columnText.addElement(createCleanParagraph(txt1,groupFontSize,true,txt2,renseignementFontSize,false));
          columnText.addElement(createCleanParagraph(txt1, groupFontSize, true));
          columnText.addElement(createCleanParagraph(txt2, renseignementFontSize, false));
          columnText.setYLine(previousPos);
        }

        columnText.setText(null);
        // columnText.addElement(createCleanParagraph(txt1,groupFontSize,true,txt2,renseignementFontSize,false));
        columnText.addElement(createCleanParagraph(txt1, groupFontSize, true));
        columnText.addElement(createCleanParagraph(txt2, renseignementFontSize, false));
        columnText.setYLine(previousPos);
        columnText.go(false);
      }

      {
        columnText = new ColumnText(cb);

        barcodeTop = barcodeTop - 12f;
        columnText.setSimpleColumn(left, barcodeTop, right, barcodeBottom);
        float barcodeHeight = barcodeTop - barcodeBottom;
        // cb.rectangle(left, barcodeTop - barcodeHeight, width, barcodeHeight);
        // cb.stroke();

        columnText.setExtraParagraphSpace(0f);
        columnText.setAdjustFirstLine(false);
        columnText.setIndent(0);

        float previousPos = columnText.getYLine();
        columnText.setText(null);
        columnText.addElement(
            createCleanBarcode(cb, participant.getNumero(), width, barcodeHeight));
        columnText.go(false);
      }

      document.newPage();
    }

    document.close();
  }
Пример #10
0
  private void openPrintableView() {
    /*
    JFrame d = new JFrame();
    d.setSize(540, 480);
    d.setTitle("Version Imprimible");
    d.setLayout(new BorderLayout());*/

    try {
      // Creating document
      Document doc = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
      File temp = File.createTempFile(new GregorianCalendar().getTimeInMillis() + "", ".pdf");
      temp.deleteOnExit();

      PdfWriter.getInstance(doc, new FileOutputStream(temp));
      doc.open();

      Font nf = new Font(Font.FontFamily.UNDEFINED, 11, Font.NORMAL);
      Font bf = new Font(Font.FontFamily.UNDEFINED, 12, Font.BOLD);

      Phrase p1 =
          new Phrase(getPrintableTitle(), new Font(Font.FontFamily.UNDEFINED, 24, Font.BOLD));
      Phrase p2 = new Phrase("Nombre:  ", bf);
      Phrase p2_0 = new Phrase(App.user.getName(), nf);

      Paragraph parag = new Paragraph();
      parag.add(p2);
      parag.add(p2_0);

      Phrase p3 = new Phrase("E-mail:  ", bf);
      Phrase p3_0 = new Phrase(App.user.getMail(), nf);

      Paragraph parag_0 = new Paragraph();
      parag_0.add(p3);
      parag_0.add(p3_0);

      PdfPTable pTable = new PdfPTable(tm.getColumnCount());
      pTable.setWidthPercentage(100f);

      if (getWidthsPrintableView() != null) pTable.setWidths(getWidthsPrintableView());

      for (int i = 0; i < tm.getColumnCount(); i++) {
        Phrase p = new Phrase(tm.getColumnName(i), bf);
        PdfPCell cell = new PdfPCell(p);
        cell.setGrayFill(.8f);
        pTable.addCell(cell);
      }

      for (int i = 0; i < tm.getRowCount(); i++)
        for (int j = 0; j < tm.getColumnCount(); j++) {
          Phrase p = new Phrase(tm.getValueAt(i, j) + "", nf);
          PdfPCell cell = new PdfPCell(p);
          cell.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);

          pTable.addCell(cell);
        }

      doc.add(new Paragraph(p1));
      doc.add(new Paragraph("\n"));
      doc.add(parag);
      doc.add(parag_0);
      doc.add(new Paragraph("\n"));
      doc.add(pTable);

      doc.close();

      // open system editor
      Desktop.getDesktop().open(temp);
      /*
      //Reading document
      Viewer v = new Viewer();
      v.setDocumentInputStream(new FileInputStream(temp));
      v.activate();
      d.add(v);*/
    } catch (Exception e) {
      e.printStackTrace();
    }
    /*
    d.setLocationRelativeTo(null);
    d.setVisible(true);*/
  }