Ejemplo n.º 1
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();
  }
Ejemplo n.º 2
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();
 }
Ejemplo n.º 3
0
  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();
  }
 public void finishText() {
   contentByte.endText();
 }
  public void onEndPage(PdfWriter pdfWriter, Document document) {
    pageNum++; // 页面计数
    if (needNotFootAndHead && pageNum >= needNotFootAndHeadPageNum) {
      return;
    }

    PdfContentByte pdfContByte = pdfWriter.getDirectContent();
    pdfContByte.saveState();
    pdfContByte.setGState(pdfGState);
    pdfContByte.setFontAndSize(baseFont, 48);
    pdfContByte.endText();

    Image barCodeImge = code39.createImageWithBarcode(pdfContByte, null, null);

    try {
      pdfContByte.addImage(
          headerImage,
          headerImage.getWidth() / 2,
          0,
          0,
          headerImage.getHeight() / 2,
          document.left() + 65,
          document.top() + 10);
      pdfContByte.addImage(
          barCodeImge,
          barCodeImge.getWidth(),
          0,
          0,
          barCodeImge.getHeight(),
          document.left() + 35,
          document.bottom() - 26);
    } catch (Exception ex) {
      throw new ExceptionConverter(ex);
    }
    pdfContByte.restoreState();
    pdfContByte.saveState();

    String headFootText = "保险合同号:" + this.contNo;
    float headTextPos = document.top() + 10;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 10);
    pdfContByte.setTextMatrix(document.right() - 175, headTextPos);
    pdfContByte.showText(headFootText);
    pdfContByte.endText();
    pdfContByte.saveState();

    //		cell.setBorder(Rectangle.BOTTOM);

    //		String metLife = "中美大都会人寿保险有限公司";
    //		float footTextPos = document.bottom()-12;
    //		pdfContByte.beginText();
    //		pdfContByte.setFontAndSize(baseFont, 7);
    //		pdfContByte.setTextMatrix(document.left()+50, footTextPos);
    //		pdfContByte.showText(metLife);
    //		pdfContByte.endText();
    //		pdfContByte.saveState();

    String shanghaimetLife = "中美联泰大都会人寿保险有限公司";
    float shanghaifootText = document.bottom();
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.left() + 35, shanghaifootText);
    pdfContByte.showText(shanghaimetLife);
    pdfContByte.endText();
    pdfContByte.saveState();

    String shanghaimetLifeAddress = "                  联系地址:上海市黄浦区黄陂北路227号中区广场11楼";
    float shanghaifootTextAddPos = document.bottom();
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 190, shanghaifootTextAddPos);
    pdfContByte.showText(shanghaimetLifeAddress);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeAddress = "北京东城区东长安街一号东方广场东方经贸城东二办公楼12层";
    float footTextAddPos = document.bottom() - 8;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 190, footTextAddPos);
    pdfContByte.showText(metLifeAddress);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeCustSer = "客户服务热线:400 818 8168";
    float footTextCSPos = document.bottom() - 16;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 85, footTextCSPos);
    pdfContByte.showText(metLifeCustSer);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeSite = "http://www.metlife.com.cn/";
    float footTextSTPos = document.bottom() - 24;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 75, footTextSTPos);
    pdfContByte.showText(metLifeSite);
    pdfContByte.endText();
    pdfContByte.saveState();

    //		String pageNumText = "第 " + pdfWriter.getPageNumber() + " 页";
    String pageNumText = String.valueOf(pdfWriter.getPageNumber());
    float textBase = document.bottom() - 2;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 9);
    pdfContByte.setTextMatrix(document.left() + 285, textBase);
    pdfContByte.showText(pageNumText);
    pdfContByte.endText();
    pdfContByte.saveState();
  }
Ejemplo n.º 6
0
  public static void concatPDFs(
      List<InputStream> streamOfPDFFiles,
      InputStream fs,
      OutputStream outputStream,
      boolean paginate)
      throws IOException {

    Document document = new Document(new PdfReader(fs).getPageSize(1));
    try {
      List<InputStream> pdfs = streamOfPDFFiles;
      List<PdfReader> readers = new ArrayList<PdfReader>();
      int totalPages = 0;
      Iterator<InputStream> iteratorPDFs = pdfs.iterator();

      // Create Readers for the pdfs.
      while (iteratorPDFs.hasNext()) {
        InputStream pdf = iteratorPDFs.next();
        PdfReader pdfReader = new PdfReader(pdf);
        readers.add(pdfReader);
        totalPages += pdfReader.getNumberOfPages();
      }
      // Create a writer for the outputstream
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);

      document.open();
      BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
      PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
      // data

      PdfImportedPage page;
      int currentPageNumber = 0;
      int pageOfCurrentReaderPDF = 0;
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();

      // Loop through the PDF files and add to the output.
      while (iteratorPDFReader.hasNext()) {
        PdfReader pdfReader = iteratorPDFReader.next();

        // Create a new page in the target for each source page.
        while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
          document.newPage();
          pageOfCurrentReaderPDF++;
          currentPageNumber++;
          page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
          cb.addTemplate(page, 0, 0);

          // Code for pagination.
          if (paginate) {
            cb.beginText();
            cb.setFontAndSize(bf, 9);
            cb.showTextAligned(
                PdfContentByte.ALIGN_CENTER,
                "" + currentPageNumber + " of " + totalPages,
                520,
                5,
                0);
            cb.endText();
          }
        }
        pageOfCurrentReaderPDF = 0;
      }
      outputStream.flush();
      document.close();
      outputStream.close();
    } catch (Exception e) {
      log.error(e.getLocalizedMessage(), e);
    } finally {
      if (document.isOpen()) document.close();
      try {
        if (outputStream != null) outputStream.close();
      } catch (IOException ioe) {
        log.error(ioe.getLocalizedMessage(), ioe);
      }
    }
  }
Ejemplo n.º 7
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();
    }
  }