private ByteArrayOutputStream getPdfData(
     JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     String[] colHeader = getColHeader();
     String[] colIndex = getColIndexes();
     String[] val = getColValues(colHeader, data);
     String[] resources = getResourcesColHeader(res, data);
     String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"};
     Document document = null;
     if (landscape) {
       Rectangle recPage = new Rectangle(PageSize.A4.rotate());
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     } else {
       Rectangle recPage = new Rectangle(PageSize.A4);
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     }
     PdfWriter writer = PdfWriter.getInstance(document, baos);
     writer.setPageEvent(new EndPage());
     document.open();
     if (showLogo) {
       getCompanyDetails(request);
       addComponyLogo(document, request);
     }
     addTitleSubtitle(document);
     addTable(data, resources, colIndex, colHeader, mainHeader, val, document);
     document.close();
     writer.close();
     baos.close();
   } catch (ConfigurationException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (DocumentException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (IOException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   }
   return baos;
 }
Esempio n. 2
0
 /*
  * crea un file pdf contenente lo stack trace dell'eccezione
  */
 private void createErrorFile(String url, File outputFile, Exception exception) {
   Document document = new Document();
   PdfWriter pdfwriter = null;
   try {
     pdfwriter = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
     document.open();
     StringBuilder buffer = new StringBuilder("Non è stato possibile generare");
     buffer.append(" il file pdf per l'URL\n\n");
     buffer.append(url);
     buffer.append("\n\na causa del seguente errore:\n\n");
     document.add(new Paragraph(buffer.toString()));
     StringWriter stringWriter = new StringWriter();
     exception.printStackTrace(new PrintWriter(stringWriter));
     document.add(new Paragraph(stringWriter.toString()));
     document.close();
     pdfwriter.close();
   } catch (FileNotFoundException | DocumentException e) {
     log.error("errore di scrittura del file di errore", e);
   }
 }
Esempio n. 3
0
  public void createPdf() throws ClassNotFoundException, SQLException {
    /*Declaramos documento como un objeto Document
    Asignamos el tamaño de hoja y los margenes */
    Document documento = new Document(PageSize.A4.rotate(), 1, 1, 20, 36);

    // writer es declarado como el método utilizado para escribir en el archivo
    PdfWriter writer = null;

    try {
      // Obtenemos la instancia del archivo a utilizar

      String filename =
          "C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/documentos/reporteAutorizacion.pdf";

      File fichero = new File(filename);

      if (fichero.exists()) {
        System.out.println("El fichero  existe222222222");
        fichero.delete();
        System.out.println("El fichero elimino");
      } else {
        System.out.println("el fichero no existe");
      }

      writer = PdfWriter.getInstance(documento, new FileOutputStream(filename));

    } catch (Exception ex) {
      System.out.println("NO creooooo");
      ex.getMessage();
    }

    // Declaramos una instancia de los eventos en HeaderFooter
    HeaderFooter event = new HeaderFooter();
    writer.setPageEvent(event);

    // Agregamos un titulo al archivo
    documento.addTitle("ARCHIVO PDF");

    // Agregamos el autor del archivo
    documento.addAuthor("PROVIAS NACIONAL");

    // Abrimos el documento para edición
    documento.open();
    try {
      // Declaramos un texto como Paragraph
      // Le podemos dar formado como alineación, tamaño y color a la fuente.
      Paragraph title1 = new Paragraph();
      title1.setAlignment(Element.ALIGN_CENTER);

      PdfPTable ta1 = new PdfPTable(2);
      ta1.setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
      ta1.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

      PdfPCell cel1 = new PdfPCell();
      com.lowagie.text.Image image =
          com.lowagie.text.Image.getInstance("D:/Provias/images/imgExports.jpg");
      // image.setWidthPercentage(500);
      cel1.addElement(image);
      cel1.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel1.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel1.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel1);
      PdfPCell cel2 = new PdfPCell();

      cel2.addElement(
          new Phrase(
              "Reporte de Autorizaciones Especiales",
              FontFactory.getFont(
                  FontFactory.HELVETICA, 12, Font.BOLD, new CMYKColor(0, 0, 0, 100))));
      cel2.setFixedHeight(90);
      cel2.setHorizontalAlignment(Element.ALIGN_CENTER);
      cel2.setVerticalAlignment(Element.ALIGN_MIDDLE);
      cel2.setBorder(Rectangle.NO_BORDER);
      ta1.addCell(cel2);

      float[] columnWidths1 = new float[] {180f, 100f};
      ta1.setWidths(columnWidths1);
      title1.add(ta1);

      // Agregamos el texto al documento
      documento.add(title1);

      // Agregamos un salto de linea
      documento.add(new Paragraph(" "));

      // Agregamos la tabla al documento haciendo
      // la llamada al método tabla()
      documento.add(tabla());
    } catch (Exception ex) {
      System.out.println("Por!!");
      ex.getMessage();
    }

    documento.close(); // Cerramos el documento
    writer.close(); // Cerramos writer
  }
  @Override
  public boolean performFinish() {

    // create the document
    Rectangle suggestedPageSize = getITextPageSize(page1.getPageSize());
    Rectangle pageSize = rotatePageIfNecessary(suggestedPageSize); // rotate if we need landscape

    Document document = new Document(pageSize);

    try {

      // Basic setup of the Document, and get instance of the iText Graphics2D
      //   to pass along to uDig's standard "printing" code.
      String outputFile =
          page1.getDestinationDir()
              + System.getProperty("file.separator")
              + //$NON-NLS-1$
              page1.getOutputFile();
      PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
      document.open();
      Graphics2D graphics = null;
      Template template = getTemplate();

      int i = 0;
      int numPages = 1;
      do {

        // sets the active page
        template.setActivePage(i);

        PdfContentByte cb = writer.getDirectContent();

        Page page = makePage(pageSize, document, template);

        graphics = cb.createGraphics(pageSize.getWidth(), pageSize.getHeight());

        // instantiate a PrinterEngine (pass in the Page instance)
        PrintingEngine engine = new PrintingEngine(page);

        // make page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        java.awt.print.Paper awtPaper = new java.awt.print.Paper();
        awtPaper.setSize(pageSize.getWidth() * 3, pageSize.getHeight() * 3);
        awtPaper.setImageableArea(0, 0, pageSize.getWidth(), pageSize.getHeight());
        pageFormat.setPaper(awtPaper);

        // run PrinterEngine's print function
        engine.print(graphics, pageFormat, 0);

        graphics.dispose();
        document.newPage();
        if (i == 0) {
          numPages = template.getNumPages();
        }
        i++;

      } while (i < numPages);

      // cleanup
      document.close();
      writer.close();
    } catch (DocumentException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    } catch (PrinterException e) {
      e.printStackTrace();
    }
    return true;
  }
Esempio n. 5
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    WebApplicationContext ctx =
        WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());

    CourseManager manager = (CourseManager) ctx.getBean("courseManager");
    HttpSession session = request.getSession(false);
    boolean b = false;
    if (request.getParameter("count") != null) {
      b = true;
    }

    List students = (List) session.getAttribute("students");

    ByteArrayOutputStream ba = new ByteArrayOutputStream();

    try {
      Document document = new Document(PageSize.A6.rotate(), 5, 5, 5, 5);

      PdfWriter writer = PdfWriter.getInstance(document, ba);
      document.open();
      Image image = null;

      Clazz clazz;
      Student stmd;
      String SchoolName;
      String DeptName;
      StringBuilder StudentNo;

      Map map;
      Map StmdCardNum;

      // writer = PdfWriter.getInstance(document, ba);
      PdfContentByte cb = writer.getDirectContent();
      BaseFont bf = BaseFont.createFont("/kaiu.ttf", "Identity-H", BaseFont.EMBEDDED);

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

        stmd =
            (Student)
                manager
                    .hqlGetBy(
                        "FROM Student WHERE studentNo='"
                            + ((Map) students.get(i)).get("student_no")
                            + "'")
                    .get(0);
        clazz =
            (Clazz)
                manager.hqlGetBy("FROM Clazz WHERE ClassNo='" + stmd.getDepartClass() + "'").get(0);
        map =
            manager.ezGetMap(
                "SELECT * FROM dept WHERE no='" + clazz.getClassNo().substring(0, 4) + "'");

        try { // 系所名
          DeptName = map.get("fname").toString();
        } catch (Exception e) {
          DeptName = "";
        }
        try { // 部制名
          SchoolName = map.get("school_name").toString();
        } catch (Exception e) {
          SchoolName = "";
        }
        StudentNo = new StringBuilder(stmd.getStudentNo());
        // List list=manager.hqlGetBy("FROM StdImage WHERE studentNo='"+StudentNo+"'");

        /*
        if(b&&manager.testOnlineServer()){//寫入補發記錄
        	try{
        		//真實學號
        		manager.executeSql("INSERT INTO StmdCardNum (student_no, card_num)VALUES('"+stmd.getStudentNo()+"', 1)");
        	}catch(Exception e){
        		manager.executeSql("UPDATE StmdCardNum SET card_num=card_num+1 WHERE student_no='"+stmd.getStudentNo()+"'");
        	}
        	StudentNo.append(manager.ezGetString("SELECT card_num FROM StmdCardNum WHERE student_no='"+stmd.getStudentNo()+"'"));
        	sendMailToLib(stmd, StudentNo.toString(), request);
        }else{
        	//檢查是否已發卡
        	StmdCardNum=manager.ezGetMap("SELECT * FROM StmdCardNum WHERE student_no='"+stmd.getStudentNo()+"'");
        	if(StmdCardNum!=null){
        		StudentNo.append(manager.ezGetString("SELECT card_num FROM StmdCardNum WHERE student_no='"+stmd.getStudentNo()+"'"));
        	}
        }
        */

        StmdCardNum = manager.ezGetMap("SELECT * FROM StmdCardNum WHERE student_no='");

        // 學號不滿8碼補空白, 未來改為9碼時?
        if (StudentNo.length() <= 8) {
          for (int j = StudentNo.length(); j < 8; j++) {
            StudentNo.append(" ");
          }
        }
        // 照片
        try {
          image = getImage(StudentNo.toString());
        } catch (Exception e) {
          continue;
        }
        if (image == null) continue;

        image.scaleAbsolute(54.94f, 74.37f);
        image.setAbsolutePosition(18, 166);

        // 條碼
        Barcode39 code39 = new Barcode39();
        code39.setCode(StudentNo.toString());
        code39.setBarHeight(20);
        code39.setX(0.95f);

        code39.setStartStopText(false);
        code39.setGuardBars(false);
        code39.setExtended(false);
        code39.setChecksumText(false);
        code39.setSize(-1f);
        Image imageCode39 = code39.createImageWithBarcode(cb, null, null);

        imageCode39.setAbsolutePosition(83.15f, 152);

        cb.setColorStroke(Color.white);
        cb.rectangle(18, 150, 54.94f, 9); // 30
        cb.setLineWidth(10);
        cb.stroke();

        cb.closePath();
        cb.closePathEoFillStroke();
        cb.closePathFillStroke();
        cb.closePathStroke();

        // 文字

        cb.beginText(); // 部制
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, SchoolName, 118, 229, 0);
        cb.endText();

        cb.beginText(); // 科系
        cb.setFontAndSize(bf, 10);
        if (DeptName.length() >= 9) {
          cb.setFontAndSize(bf, 8);
        }
        if (DeptName.length() >= 14) {
          cb.setFontAndSize(bf, 6);
        }

        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, DeptName, 118, 215, 0);
        cb.endText();

        cb.beginText(); // 學號
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, stmd.getStudentNo(), 118, 201, 0);
        cb.endText();

        cb.beginText(); // 姓名
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, stmd.getStudentName(), 118, 187, 0);
        cb.endText();

        document.add(image);
        document.add(imageCode39);
        document.newPage();
        // bf=null;
      }

      document.close();
      writer.close();

      response.setHeader(
          "Content-Disposition", "attachment;filename=EmplCard" + Math.random() * 10 + ".pdf");
      response.setContentLength(ba.size());
      response.flushBuffer();
      ServletOutputStream out = response.getOutputStream();
      ba.writeTo(out);
      ba.close();
      out.flush();

    } catch (Exception e) {
      e.printStackTrace();
      try {
        Document document = new Document(PageSize.A6.rotate(), 5, 5, 5, 5);
        PdfWriter writer = PdfWriter.getInstance(document, ba);
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont("/kaiu.ttf", "Identity-H", BaseFont.EMBEDDED);
        cb.beginText(); // 部制
        cb.setFontAndSize(bf, 10);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "讀取資料有誤:" + e, 120, 226, 0);
        cb.endText();
        // document.add(cb );
        document.close();
        document = null;
      } catch (DocumentException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      response.setContentType("text/html; charset=UTF-8");
      response.setContentType("application/pdf");
      response.setHeader("Content-disposition", "attachment;filename=TechTimetable.pdf");
      response.setContentLength(ba.size());
      ServletOutputStream out = response.getOutputStream();
      ba.writeTo(out);
      out.flush();
    }
  }