java.util.EmptyStackException#com.lowagie.text.DocumentException源码实例Demo

下面列出了java.util.EmptyStackException#com.lowagie.text.DocumentException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private void writeGraph() throws IOException, DocumentException {
	final JRobin jrobin = collector.getJRobin(graphName);
	if (jrobin != null) {
		final byte[] img = jrobin.graph(range, 960, 400);
		final Image image = Image.getInstance(img);
		image.scalePercent(50);

		final PdfPTable table = new PdfPTable(1);
		table.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.setWidthPercentage(100);
		table.getDefaultCell().setBorder(0);
		table.addCell("\n");
		table.addCell(image);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(new Phrase(getString("graph_units"), cellFont));
		addToDocument(table);
	} else {
		// just in case request is null and collector.getJRobin(graphName) is null, we must write something in the document
		addToDocument(new Phrase("\n", cellFont));
	}
}
 
源代码2 项目: openemm   文件: AdminController.java
@RequestMapping("/list/export/pdf.action")
public ResponseEntity<InputStreamResource> exportPdf(final ComAdmin admin, final AdminListForm form)
        throws IOException, DocumentException {

    String pdfFileNameToDownload = "users.pdf";
    byte[] pdfFileBytes = pdfService
            .writeUsersToPdfAndGetByteArray(getAdminListFromAdminListForm(admin, form, Integer.MAX_VALUE).getList());

    String description = "Page: " + form.getPage()
            + ", sort: " + form.getSort()
            + ", direction: " + form.getDir();
    userActivityLogService.writeUserActivityLog(admin, "export admins pdf", description, LOGGER);

    return ResponseEntity.ok()
            .contentLength(pdfFileBytes.length)
            .contentType(MediaType.parseMediaType("application/pdf"))
            .header(HttpHeaders.CONTENT_DISPOSITION,
                    HttpUtils.getContentDispositionHeaderContent(pdfFileNameToDownload))
            .body(new InputStreamResource(new ByteArrayInputStream(pdfFileBytes)));
}
 
源代码3 项目: birt   文件: TrueTypeFont.java
private void fillHHea( ) throws DocumentException, IOException
{
	int[] tableLocation = getTableLocation( "hhea" );
	rf.seek( tableLocation[0] + 4 );
	hhea.Ascender = rf.readShort( );
	hhea.Descender = rf.readShort( );
	hhea.LineGap = rf.readShort( );
	hhea.advanceWidthMax = rf.readUnsignedShort( );
	hhea.minLeftSideBearing = rf.readShort( );
	hhea.minRightSideBearing = rf.readShort( );
	hhea.xMaxExtent = rf.readShort( );
	hhea.caretSlopeRise = rf.readShort( );
	hhea.caretSlopeRun = rf.readShort( );
	rf.skipBytes( 12 );
	hhea.numberOfHMetrics = rf.readUnsignedShort( );
}
 
源代码4 项目: jasperreports   文件: JRPdfExporter.java
/**
 *
 */
protected void exportPage(JRPrintPage page) throws JRException, DocumentException, IOException
{
	tagHelper.startPage();
	
	Collection<JRPrintElement> elements = page.getElements();
	exportElements(elements);

	if (radioGroups != null)
	{
		for (PdfFormField radioGroup : radioGroups.values())
		{
			pdfWriter.addAnnotation(radioGroup);
		}
		radioGroups = null;
		radioFieldFactories = null; // radio groups that overflow unto next page don't seem to work; reset everything as it does not make sense to keep them
	}
	
	tagHelper.endPage();

	JRExportProgressMonitor progressMonitor = getCurrentItemConfiguration().getProgressMonitor();
	if (progressMonitor != null)
	{
		progressMonitor.afterPageExport();
	}
}
 
源代码5 项目: itext2   文件: RtfImage.java
/**
 * Constructs a RtfImage for an Image.
 * 
 * @param doc The RtfDocument this RtfImage belongs to
 * @param image The Image that this RtfImage wraps
 * @throws DocumentException If an error occurred accessing the image content
 */
public RtfImage(RtfDocument doc, Image image) throws DocumentException
{
    super(doc);
    imageType = image.getOriginalType();
    if (!(imageType == Image.ORIGINAL_JPEG || imageType == Image.ORIGINAL_BMP
            || imageType == Image.ORIGINAL_PNG || imageType == Image.ORIGINAL_WMF || imageType == Image.ORIGINAL_GIF)) {
        throw new DocumentException("Only BMP, PNG, WMF, GIF and JPEG images are supported by the RTF Writer");
    }
    alignment = image.getAlignment();
    width = image.getWidth();
    height = image.getHeight();
    plainWidth = image.getPlainWidth();
    plainHeight = image.getPlainHeight();
    this.imageData = getImageData(image);
}
 
源代码6 项目: kfs   文件: CustomerLoadServiceImpl.java
protected void writeCustomerSectionResult(Document pdfDoc, String resultLine) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 8, Font.BOLD);

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(Element.ALIGN_LEFT);
    paragraph.add(new Chunk(resultLine, font));

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}
 
源代码7 项目: javamelody   文件: PdfCoreReport.java
private void writeJobs(Counter rangeJobCounter, boolean includeDetails)
		throws DocumentException, IOException {
	String eol = "";
	for (final JavaInformations javaInformations : javaInformationsList) {
		if (!javaInformations.isJobEnabled()) {
			continue;
		}
		final List<JobInformations> jobInformationsList = javaInformations
				.getJobInformationsList();
		final String msg = getFormattedString("jobs_sur", jobInformationsList.size(),
				javaInformations.getHost(), javaInformations.getCurrentlyExecutingJobCount());
		addToDocument(new Phrase(eol + msg, boldFont));

		if (includeDetails) {
			new PdfJobInformationsReport(jobInformationsList, rangeJobCounter, getDocument())
					.toPdf();
		}
		eol = "\n";
	}
}
 
源代码8 项目: pentaho-reporting   文件: PdfDocumentWriter.java
public void processLogicalPage( final LogicalPageKey key, final LogicalPageBox logicalPage ) throws DocumentException {

    final float width = (float) StrictGeomUtility.toExternalValue( logicalPage.getPageWidth() );
    final float height = (float) StrictGeomUtility.toExternalValue( logicalPage.getPageHeight() );

    final Rectangle pageSize = new Rectangle( width, height );

    final Document document = getDocument();
    document.setPageSize( pageSize );
    document.setMargins( 0, 0, 0, 0 );

    if ( awaitOpenDocument ) {
      document.open();
      awaitOpenDocument = false;
    }

    final Graphics2D graphics = new PdfGraphics2D( writer.getDirectContent(), width, height, metaData );
    // and now process the box ..
    final PdfLogicalPageDrawable logicalPageDrawable = createLogicalPageDrawable( logicalPage, null );
    logicalPageDrawable.draw( graphics, new Rectangle2D.Double( 0, 0, width, height ) );

    graphics.dispose();

    document.newPage();
  }
 
源代码9 项目: birt   文件: PDFPage.java
protected PdfTemplate transSVG( String svgPath, byte[] svgData, float x,
		float y, float height, float width, String helpText )
		throws IOException, DocumentException
{
	PdfTemplate template = contentByte.createTemplate( width, height );
	Graphics2D g2D = template.createGraphics( width, height );

	PrintTranscoder transcoder = new PrintTranscoder( );
	if ( null != svgData && svgData.length > 0 )
	{
		transcoder.transcode( new TranscoderInput(
				new ByteArrayInputStream( svgData ) ), null );
	}
	else if ( null != svgPath )
	{
		transcoder.transcode( new TranscoderInput( svgPath ), null );
	}
	PageFormat pg = new PageFormat( );
	Paper p = new Paper( );
	p.setSize( width, height );
	p.setImageableArea( 0, 0, width, height );
	pg.setPaper( p );
	transcoder.print( g2D, pg, 0 );
	g2D.dispose( );
	return template;
}
 
源代码10 项目: itext2   文件: PdfPCell.java
/**
   * Consumes part of the content of the cell.
   * @param	height	the hight of the part that has to be consumed
   * @since	2.1.6
   */
  void consumeHeight(float height) {
      float rightLimit = getRight() - getEffectivePaddingRight();
      float leftLimit = getLeft() + getEffectivePaddingLeft();
      float bry = height - getEffectivePaddingTop() - getEffectivePaddingBottom();
      if (getRotation() != 90 && getRotation() != 270) {
          column.setSimpleColumn(leftLimit, bry + 0.001f,	rightLimit, 0);
      }
      else {
      	column.setSimpleColumn(0, leftLimit, bry + 0.001f, rightLimit);
      }
      try {
      	column.go(true);
} catch (DocumentException e) {
	// do nothing
}
  }
 
源代码11 项目: gcs   文件: PdfPCell.java
/**
   * Consumes part of the content of the cell.
   * @param	height	the hight of the part that has to be consumed
   * @since	2.1.6
   */
  void consumeHeight(float height) {
      float rightLimit = getRight() - getEffectivePaddingRight();
      float leftLimit = getLeft() + getEffectivePaddingLeft();
      float bry = height - getEffectivePaddingTop() - getEffectivePaddingBottom();
      if (getRotation() != 90 && getRotation() != 270) {
          column.setSimpleColumn(leftLimit, bry + 0.001f,	rightLimit, 0);
      }
      else {
      	column.setSimpleColumn(0, leftLimit, bry + 0.001f, rightLimit);
      }
      try {
      	column.go(true);
} catch (DocumentException e) {
	// do nothing
}
  }
 
源代码12 项目: itext2   文件: AcroFields.java
/**
    * Sets different values in a list selection.
    * No appearance is generated yet; nor does the code check if multiple select is allowed.
    * 
    * @param	name	the name of the field
    * @param	value	an array with values that need to be selected
    * @return	true only if the field value was changed
    * @since 2.1.4
    */
public boolean setListSelection(String name, String[] value) throws IOException, DocumentException {
       Item item = getFieldItem(name);
       if (item == null)
           return false;
       PdfName type = item.getMerged(0).getAsName(PdfName.FT);
       if (!PdfName.CH.equals(type)) {
       	return false;
       }
       String[] options = getListOptionExport(name);
       PdfArray array = new PdfArray();
       for (int i = 0; i < value.length; i++) {
       	for (int j = 0; j < options.length; j++) {
       		if (options[j].equals(value[i])) {
       			array.add(new PdfNumber(j));
       		}
       	}
       }
       item.writeToAll(PdfName.I, array, Item.WRITE_MERGED | Item.WRITE_VALUE);
       item.writeToAll(PdfName.V, null, Item.WRITE_MERGED | Item.WRITE_VALUE);
       item.writeToAll(PdfName.AP, null, Item.WRITE_MERGED | Item.WRITE_WIDGET);
       item.markUsed( this, Item.WRITE_VALUE | Item.WRITE_WIDGET );
       return true;
}
 
源代码13 项目: itext2   文件: TrueTypeFont.java
/** Creates a new TrueType font.
 * @param ttFile the location of the font on file. The file must end in '.ttf' or
 * '.ttc' but can have modifiers after the name
 * @param enc the encoding to be applied to this font
 * @param emb true if the font is to be embedded in the PDF
 * @param ttfAfm the font as a <CODE>byte</CODE> array
 * @throws DocumentException the font is invalid
 * @throws IOException the font file could not be read
 * @since	2.1.5
 */
TrueTypeFont(String ttFile, String enc, boolean emb, byte ttfAfm[], boolean justNames, boolean forceRead) throws DocumentException, IOException {
	this.justNames = justNames;
    String nameBase = getBaseName(ttFile);
    String ttcName = getTTCName(nameBase);
    if (nameBase.length() < ttFile.length()) {
        style = ttFile.substring(nameBase.length());
    }
    encoding = enc;
    embedded = emb;
    fileName = ttcName;
    fontType = FONT_TYPE_TT;
    ttcIndex = "";
    if (ttcName.length() < nameBase.length())
        ttcIndex = nameBase.substring(ttcName.length() + 1);
    if (fileName.toLowerCase().endsWith(".ttf") || fileName.toLowerCase().endsWith(".otf") || fileName.toLowerCase().endsWith(".ttc")) {
        process(ttfAfm, forceRead);
        if (!justNames && embedded && os_2.fsType == 2)
            throw new DocumentException(fileName + style + " cannot be embedded due to licensing restrictions.");
    }
    else
        throw new DocumentException(fileName + style + " is not a TTF, OTF or TTC font file.");
    if (!encoding.startsWith("#"))
        PdfEncodings.convertToBytes(" ", enc); // check if the encoding exists
    createEncoding();
}
 
源代码14 项目: itext2   文件: PdfPages.java
int reorderPages(int order[]) throws DocumentException {
    if (order == null)
        return pages.size();
    if (parents.size() > 1)
        throw new DocumentException("Page reordering requires a single parent in the page tree. Call PdfWriter.setLinearMode() after open.");
    if (order.length != pages.size())
        throw new DocumentException("Page reordering requires an array with the same size as the number of pages.");
    int max = pages.size();
    boolean temp[] = new boolean[max];
    for (int k = 0; k < max; ++k) {
        int p = order[k];
        if (p < 1 || p > max)
            throw new DocumentException("Page reordering requires pages between 1 and " + max + ". Found " + p + ".");
        if (temp[p - 1])
            throw new DocumentException("Page reordering requires no page repetition. Page " + p + " is repeated.");
        temp[p - 1] = true;
    }
    Object copy[] = pages.toArray();
    for (int k = 0; k < max; ++k) {
        pages.set(k, copy[order[k] - 1]);
    }
    return max;
}
 
源代码15 项目: itext2   文件: TrueTypeFontUnicode.java
void readCMaps() throws DocumentException, IOException {
	super.readCMaps();
    
	HashMap cmap = null;
	if (cmapExt != null) {
		cmap = cmapExt;
	} else if (cmap31 != null) {
		cmap = cmap31;
	}
    
	if (cmap != null) {
		inverseCmap = new HashMap<Integer, Integer>();
		for (Iterator iterator = cmap.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			Integer code = (Integer) entry.getKey();
			int[] metrics = (int[]) entry.getValue();
			inverseCmap.put(Integer.valueOf(metrics[0]), code);
		}
	}
}
 
源代码16 项目: itext2   文件: WritePdfTest.java
@Test
public void writeFile() throws IOException, DocumentException {
	File file = File.createTempFile("testfile", ".pdf");
	File fileWithPageNumbers = File.createTempFile("testfilewithpagenumbers", ".pdf");
	Document document = new Document();
	PdfWriter.getInstance(document, new FileOutputStream(file));
	document.open();
	for(int i = 0; i < 100; i++) {
	document.add(new Paragraph("Test"));
	}
	document.close();
	addPageNumbers(file, fileWithPageNumbers.getAbsolutePath());
	Assert.assertTrue(file.length() > 0);
	Assert.assertTrue(fileWithPageNumbers.length() > 0);
	file.delete();
	fileWithPageNumbers.delete();
}
 
源代码17 项目: unitime   文件: InstructorExamReport.java
public void printReport(ExamInstructorInfo instructor) throws DocumentException {
    TreeSet<ExamAssignmentInfo> exams = new TreeSet();
    for (ExamAssignmentInfo exam:getExams()) {
        if (exam.getPeriod()==null) continue;
        if (exam.getInstructors().contains(instructor));
    }
    if (exams.isEmpty()) return;
    printHeader();
    printReport(instructor, exams);
    lastPage();
}
 
private void writeRequest(CounterRequestContext context, PdfPCell cell, int margin)
		throws DocumentException, IOException {
	final Paragraph paragraph = new Paragraph(
			getDefaultCell().getLeading() + cellFont.getSize());
	paragraph.setIndentationLeft(margin);
	if (context.getParentCounter().getIconName() != null) {
		paragraph.add(new Chunk(getImage(context.getParentCounter().getIconName()), 0, -1));
	}
	paragraph.add(new Phrase(context.getCompleteRequestName(), cellFont));
	cell.addElement(paragraph);
}
 
源代码19 项目: kfs   文件: CashReceiptCoverSheetServiceImpl.java
/**
 * Responsible for creating a new PDF page and workspace through <code>{@link PdfContentByte}</code> for direct writing to the
 * PDF.
 *
 * @param writer The PDF writer used to write to the new page with.
 * @param reader The PDF reader used to read information from the PDF file.
 * @param pageNumber The current number of pages in the PDF file, which will be incremented by one inside this method.
 *
 * @return The PDFContentByte used to access the new PDF page.
 * @exception DocumentException
 * @exception IOException
 */
protected PdfContentByte startNewPage(PdfWriter writer, PdfReader reader, ModifiableInteger pageNumber) throws DocumentException, IOException {
    PdfContentByte retval;
    PdfContentByte under;
    Rectangle pageSize;
    Document pdfDoc;
    PdfImportedPage newPage;

    pageNumber.increment();
    pageSize = reader.getPageSize(FRONT_PAGE);
    retval = writer.getDirectContent();
    // under = writer.getDirectContentUnder();

    if (pageNumber.getInt() > FRONT_PAGE) {
        newPage = writer.getImportedPage(reader, CHECK_PAGE_NORMAL);
        setCurrentRenderingYPosition(pageSize.top(TOP_MARGIN + CHECK_DETAIL_HEADING_HEIGHT));
    }
    else {
        newPage = writer.getImportedPage(reader, FRONT_PAGE);
        setCurrentRenderingYPosition(pageSize.top(TOP_FIRST_PAGE));
    }

    pdfDoc = retval.getPdfDocument();
    pdfDoc.newPage();
    retval.addTemplate(newPage, 0, 0);
    retval.setFontAndSize(getTextFont(), 8);

    return retval;
}
 
/**
 * @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateListOfInvoicesEnvelopesPdfToPrint(java.util.Collection)
 */
@Override
public byte[] combineInvoicePdfEnvelopes(Collection<ContractsGrantsInvoiceDocument> list) throws DocumentException, IOException {
    Date runDate = new Date(new java.util.Date().getTime());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    generateCombinedPdfForEnvelopes(list, baos);
    return baos.toByteArray();
}
 
源代码21 项目: Knowage-Server   文件: PdfPTable.java
/**
 * Processes the element by adding it (or the different parts) to an
 * <CODE>ElementListener</CODE>.
 *
 * @param	listener	an <CODE>ElementListener</CODE>
 * @return	<CODE>true</CODE> if the element was processed successfully
 */
public boolean process(ElementListener listener) {
    try {
        return listener.add(this);
    }
    catch(DocumentException de) {
        return false;
    }
}
 
源代码22 项目: gcs   文件: PdfDocument.java
/**
 * Adds a <CODE>PdfWriter</CODE> to the <CODE>PdfDocument</CODE>.
 *
 * @param writer the <CODE>PdfWriter</CODE> that writes everything what is added to this
 *            document to an outputstream.
 * @throws DocumentException on error
 */
public void addWriter(PdfWriter writer) throws DocumentException {
	if (this.writer == null) {
		this.writer = writer;
		annotationsImp = new PdfAnnotationsImp(writer);
		return;
	}
	throw new DocumentException("You can only add a writer to a PdfDocument once.");
}
 
源代码23 项目: gcs   文件: MultiColumnText.java
/**
 * Add an element to be rendered in a column. Note that you can only add a <CODE>Phrase</CODE>
 * or a <CODE>Chunk</CODE> if the columns are not all simple. This is an underlying restriction
 * in {@link com.lowagie.text.pdf.ColumnText}
 *
 * @param element element to add
 * @throws DocumentException if element can't be added
 */
public void addElement(Element element) throws DocumentException {
	if (simple) {
		columnText.addElement(element);
	} else if (element instanceof Phrase) {
		columnText.addText((Phrase) element);
	} else if (element instanceof Chunk) {
		columnText.addText((Chunk) element);
	} else {
		throw new DocumentException("Can't add " + element.getClass() + " to MultiColumnText with complex columns");
	}
}
 
源代码24 项目: javamelody   文件: PdfCacheInformationsReport.java
private void addConfigurationReference() throws DocumentException {
	final Anchor ehcacheAnchor = new Anchor("Configuration reference", PdfFonts.BLUE.getFont());
	ehcacheAnchor.setName("Ehcache configuration reference");
	ehcacheAnchor.setReference(
			"http://www.ehcache.org/apidocs/2.9/net/sf/ehcache/config/CacheConfiguration.html#field_summary");
	ehcacheAnchor.setFont(PdfFonts.BLUE.getFont());
	final Paragraph ehcacheParagraph = new Paragraph();
	ehcacheParagraph.add(ehcacheAnchor);
	ehcacheParagraph.setAlignment(Element.ALIGN_RIGHT);
	addToDocument(ehcacheParagraph);
}
 
源代码25 项目: unitime   文件: PdfLegacyExamReport.java
public PdfLegacyExamReport(int mode, OutputStream out, String title, Session session, ExamType examType, Collection<SubjectArea> subjectAreas, Collection<ExamAssignmentInfo> exams) throws DocumentException, IOException {
    super(mode, out, title,
    		ApplicationProperty.ExaminationPdfReportTitle.value(examType == null ? "all" : examType.getReference(), examType == null ? "EXAMINATIONS" : examType.getLabel().toUpperCase() + " EXAMINATIONS"),
            title + " -- " + session.getLabel(), session.getLabel());
    if (subjectAreas!=null && subjectAreas.size() == 1) setFooter(subjectAreas.iterator().next().getSubjectAreaAbbreviation());
    iExams = exams;
    iSession = session;
    iExamType = examType;
    iSubjectAreas = subjectAreas;
    iDispRooms = "true".equals(System.getProperty("room","true"));
    iDispNote = "true".equals(System.getProperty("note","false"));
    iCompact = "true".equals(System.getProperty("compact", "false"));
    iNoRoom = System.getProperty("noroom", ApplicationProperty.ExaminationsNoRoomText.value());
    iDirect = "true".equals(System.getProperty("direct","true"));
    iM2d = "true".equals(System.getProperty("m2d",(examType == null || examType.getType() == ExamType.sExamTypeFinal?"true":"false")));
    iBtb = "true".equals(System.getProperty("btb","false"));
    iLimit = Integer.parseInt(System.getProperty("limit", "-1"));
    iItype = "true".equals(System.getProperty("itype", ApplicationProperty.ExaminationReportsShowInstructionalType.value()));
    iTotals = "true".equals(System.getProperty("totals","true"));
    iUseClassSuffix = "true".equals(System.getProperty("suffix", ApplicationProperty.ExaminationReportsClassSufix.value()));
    iExternal = ApplicationProperty.ExaminationReportsExternalId.isTrue();
    iDispLimits = "true".equals(System.getProperty("verlimit","true"));
    iClassSchedule = "true".equals(System.getProperty("cschedule", ApplicationProperty.ExaminationPdfReportsIncludeClassSchedule.value()));
    iDispFullTermDates = "true".equals(System.getProperty("fullterm","false"));
    iRoomDisplayNames = "true".equals(System.getProperty("roomDispNames", "true"));
    iFullTermCheckDatePattern = ApplicationProperty.ExaminationPdfReportsFullTermCheckDatePattern.isTrue();
    iMeetingTimeUseEvents = ApplicationProperty.ExaminationPdfReportsUseEventsForMeetingTimes.isTrue();
    if (System.getProperty("since")!=null) {
        try {
            iSince = new SimpleDateFormat(System.getProperty("sinceFormat","MM/dd/yy")).parse(System.getProperty("since"));
        } catch (Exception e) {
            sLog.error("Unable to parse date "+System.getProperty("since")+", reason: "+e.getMessage());
        }
    }
    setRoomCode(System.getProperty("roomcode", ApplicationProperty.ExaminationRoomCode.value()));
}
 
源代码26 项目: kfs   文件: DunningLetterServiceImpl.java
/**
 * Generates the pdf file for printing the invoices.
 *
 * @param list
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
protected void generateCombinedPdfForInvoices(Collection<ContractsGrantsInvoiceDocument> list, byte[] report, OutputStream outputStream) throws DocumentException, IOException {
    PdfCopyFields copy = new PdfCopyFields(outputStream);
    copy.open();
    copy.addDocument(new PdfReader(report));
    for (ContractsGrantsInvoiceDocument invoice : list) {
        for (InvoiceAddressDetail invoiceAddressDetail : invoice.getInvoiceAddressDetails()) {
            Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
            if (ObjectUtils.isNotNull(note) && note.getAttachment().getAttachmentFileSize() > 0) {
                copy.addDocument(new PdfReader(note.getAttachment().getAttachmentContents()));
            }
        }
    }
    copy.close();
}
 
源代码27 项目: birt   文件: TrueTypeFont.java
/**
 * Gets the Postscript font name.
 * 
 * @throws DocumentException
 *             the font is invalid
 * @throws IOException
 *             the font file could not be read
 * @return the Postscript font name
 */
String getBaseFont( ) throws DocumentException, IOException
{
	int table_location[];
	table_location = (int[]) positionTables.get( "name" );
	if ( table_location == null )
		throw new DocumentException( "Table 'name' does not exist in "
				+ fileName + style );
	rf.seek( table_location[0] + 2 );
	int numRecords = rf.readUnsignedShort( );
	int startOfStorage = rf.readUnsignedShort( );
	for ( int k = 0; k < numRecords; ++k )
	{
		int platformID = rf.readUnsignedShort( );
		int nameID = rf.readUnsignedShort( );
		int length = rf.readUnsignedShort( );
		int offset = rf.readUnsignedShort( );
		if ( nameID == 6 )
		{
			rf.seek( table_location[0] + startOfStorage + offset );
			if ( platformID != 0 && platformID != 3 )
			{
				String name = readStandardString( length );
				name = name.replace( ' ', '_' );
				return name.replace( (char)0, '_' );
			}
		}
	}
	File file = new File( fileName );
	return file.getName( ).replace( ' ', '_' );
}
 
源代码28 项目: itext2   文件: PdfCopy.java
/**
 * Constructor
 * @param document
 * @param os outputstream
 */
public PdfCopy(Document document, OutputStream os) throws DocumentException {
    super(new PdfDocument(), os);
    document.addDocListener(pdf);
    pdf.addWriter(this);
    indirectMap = new HashMap();
}
 
源代码29 项目: itext2   文件: TrueTypeFont.java
/** Extracts all the names of the names-Table
 * @throws DocumentException on error
 * @throws IOException on error
 */    
String[][] getAllNames() throws DocumentException, IOException {
    int table_location[];
    table_location = (int[])tables.get("name");
    if (table_location == null)
        throw new DocumentException("Table 'name' does not exist in " + fileName + style);
    rf.seek(table_location[0] + 2);
    int numRecords = rf.readUnsignedShort();
    int startOfStorage = rf.readUnsignedShort();
    ArrayList names = new ArrayList();
    for (int k = 0; k < numRecords; ++k) {
        int platformID = rf.readUnsignedShort();
        int platformEncodingID = rf.readUnsignedShort();
        int languageID = rf.readUnsignedShort();
        int nameID = rf.readUnsignedShort();
        int length = rf.readUnsignedShort();
        int offset = rf.readUnsignedShort();
        int pos = rf.getFilePointer();
        rf.seek(table_location[0] + startOfStorage + offset);
        String name;
        if (platformID == 0 || platformID == 3 || (platformID == 2 && platformEncodingID == 1)){
            name = readUnicodeString(length);
        }
        else {
            name = readStandardString(length);
        }
        names.add(new String[]{String.valueOf(nameID), String.valueOf(platformID),
                String.valueOf(platformEncodingID), String.valueOf(languageID), name});
        rf.seek(pos);
    }
    String thisName[][] = new String[names.size()][];
    for (int k = 0; k < names.size(); ++k)
        thisName[k] = (String[])names.get(k);
    return thisName;
}
 
protected void writeFileNameSectionTitle(com.lowagie.text.Document pdfDoc, String filenameLine) {
    Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.BOLD);

    //  file name title, get title only, on windows & unix platforms
    String fileNameOnly = filenameLine.toUpperCase();
    int indexOfSlashes = fileNameOnly.lastIndexOf("\\");
    if (indexOfSlashes < fileNameOnly.length()) {
        fileNameOnly = fileNameOnly.substring(indexOfSlashes + 1);
    }
    indexOfSlashes = fileNameOnly.lastIndexOf("/");
    if (indexOfSlashes < fileNameOnly.length()) {
        fileNameOnly = fileNameOnly.substring(indexOfSlashes + 1);
    }

    Paragraph paragraph = new Paragraph();
    paragraph.setAlignment(com.lowagie.text.Element.ALIGN_LEFT);
    Chunk chunk = new Chunk(fileNameOnly, font);
    chunk.setBackground(Color.LIGHT_GRAY, 5, 5, 5, 5);
    paragraph.add(chunk);

    //  blank line
    paragraph.add(new Chunk("", font));

    try {
        pdfDoc.add(paragraph);
    }
    catch (DocumentException e) {
        LOG.error("iText DocumentException thrown when trying to write content.", e);
        throw new RuntimeException("iText DocumentException thrown when trying to write content.", e);
    }
}