com.lowagie.text.DocumentException Java Examples

The following examples show how to use com.lowagie.text.DocumentException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WritePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example #2
Source File: CustomerLoadServiceImpl.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example #3
Source File: PdfCoreReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
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";
	}
}
 
Example #4
Source File: RtfImage.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: PdfDocumentWriter.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
  }
 
Example #6
Source File: JRPdfExporter.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 *
 */
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();
	}
}
 
Example #7
Source File: PDFPage.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: PdfPCell.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
   * 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
}
  }
 
Example #9
Source File: PdfPCell.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
   * 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
}
  }
 
Example #10
Source File: AcroFields.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
    * 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;
}
 
Example #11
Source File: TrueTypeFont.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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( );
}
 
Example #12
Source File: TrueTypeFont.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** 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();
}
 
Example #13
Source File: PdfRequestAndGraphDetailReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
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));
	}
}
 
Example #14
Source File: PdfPages.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: TrueTypeFontUnicode.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
		}
	}
}
 
Example #16
Source File: PdfPTable.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #17
Source File: PdfPTable.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #18
Source File: PdfProcessInformationsReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
@Override
void toPdf() throws DocumentException {
	writeHeader();

	writeProcessInformations();

	if (!windows) {
		addPsCommandReference();
	}
}
 
Example #19
Source File: TrueTypeFont.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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( ' ', '_' );
}
 
Example #20
Source File: PdfCopy.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #21
Source File: TrueTypeFont.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** 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;
}
 
Example #22
Source File: CustomerInvoiceWriteoffBatchServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
    }
}
 
Example #23
Source File: TablePdfTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
private PdfPTable createPdfTable(int numberOfColumns)
		throws DocumentException {

	PdfPTable table = new PdfPTable(numberOfColumns);

	table.getDefaultCell().setBorder(1);
	table.setSpacingBefore(0f);
	table.setSpacingAfter(0);
	table.setKeepTogether(true);
	table.getDefaultCell().setUseAscender(true);
	table.getDefaultCell().setUseDescender(true);
	table.getDefaultCell().setUseBorderPadding(false);

	return table;
}
 
Example #24
Source File: PdfContentByte.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds an <CODE>Image</CODE> to the page. The <CODE>Image</CODE> must have
 * absolute positioning.
 * @param image the <CODE>Image</CODE> object
 * @throws DocumentException if the <CODE>Image</CODE> does not have absolute positioning
 */
public void addImage(Image image) throws DocumentException {
    if (!image.hasAbsolutePosition())
        throw new DocumentException("The image must have absolute positioning.");
    float matrix[] = image.matrix();
    matrix[Image.CX] = image.absoluteX() - matrix[Image.CX];
    matrix[Image.CY] = image.absoluteY() - matrix[Image.CY];
    addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
}
 
Example #25
Source File: PdfContentByte.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds an <CODE>Image</CODE> to the page. The positioning of the <CODE>Image</CODE>
 * is done with the transformation matrix. To position an <CODE>image</CODE> at (x,y)
 * use addImage(image, image_width, 0, 0, image_height, x, y).
 * @param image the <CODE>Image</CODE> object
 * @param a an element of the transformation matrix
 * @param b an element of the transformation matrix
 * @param c an element of the transformation matrix
 * @param d an element of the transformation matrix
 * @param e an element of the transformation matrix
 * @param f an element of the transformation matrix
 * @throws DocumentException on error
 */
public void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException {
    try {
        
        if (image.isImgTemplate()) {
            writer.addDirectImageSimple(image);
            PdfTemplate template = image.templateData();
            float w = template.getWidth();
            float h = template.getHeight();
            if (image.getLayer() != null)
                beginLayer(image.getLayer());
            addTemplate(template, a / w, b / w, c / h, d / h, e, f);
            if (image.getLayer() != null)
                endLayer();
        }
        else {
            PdfName name;
            PageResources prs = getPageResources();
            Image maskImage = image.getImageMask();
            if (maskImage != null) {
                name = writer.addDirectImageSimple(maskImage);
                prs.addXObject(name, writer.getImageReference(name));
            }
            name = writer.addDirectImageSimple(image);
            name = prs.addXObject(name, writer.getImageReference(name));
            content.append("q ");
            content.append(a).append(' ');
            content.append(b).append(' ');
            content.append(c).append(' ');
            content.append(d).append(' ');
            content.append(e).append(' ');
            content.append(f).append(" cm ");
            content.append(name.getBytes()).append(" Do Q").append_i(separator);
        }
    }
    catch (Exception ee) {
        throw new DocumentException(ee);
    }
}
 
Example #26
Source File: PdfCounterReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
void writeRequests(String childCounterName, List<CounterRequest> requestList)
		throws DocumentException, IOException {
	assert requestList != null;
	writeHeader(childCounterName);

	for (final CounterRequest request : requestList) {
		nextRow();
		writeRequest(request);
	}
	addTableToDocument();

	// débit et liens
	writeFooter();
}
 
Example #27
Source File: PdfCoreReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void writeCurrentRequestsDetails(
		List<PdfCounterRequestContextReport> pdfCounterRequestContextReports)
		throws IOException, DocumentException {
	for (final PdfCounterRequestContextReport pdfCounterRequestContextReport : pdfCounterRequestContextReports) {
		pdfCounterRequestContextReport.writeContextDetails();
	}
	if (pdfCounterRequestContextReports.isEmpty()) {
		addToDocument(new Phrase(getString("Aucune_requete_en_cours"), normalFont));
	}
}
 
Example #28
Source File: PaperightPdfConverter.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
public String cropPdf(String pdfFilePath) throws DocumentException, IOException, Exception {
	String filename = FilenameUtils.getBaseName(pdfFilePath) + "_cropped." + FilenameUtils.getExtension(pdfFilePath);
	filename = FilenameUtils.concat(System.getProperty("java.io.tmpdir"), filename);
	PdfReader reader = new PdfReader(pdfFilePath);
	try {
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(filename));
		try {
			for (int i = 1; i <= reader.getNumberOfPages(); i++) {
				PdfDictionary pdfDictionary = reader.getPageN(i);
				PdfArray cropArray = new PdfArray();
				Rectangle box = getSmallestBox(reader, i);
				//Rectangle cropbox = reader.getCropBox(i);
				if (box != null) {
					cropArray.add(new PdfNumber(box.getLeft()));
					cropArray.add(new PdfNumber(box.getBottom()));
					cropArray.add(new PdfNumber(box.getLeft() + box.getWidth()));
					cropArray.add(new PdfNumber(box.getBottom() + box.getHeight()));
					pdfDictionary.put(PdfName.CROPBOX, cropArray);
					pdfDictionary.put(PdfName.MEDIABOX, cropArray);
					pdfDictionary.put(PdfName.TRIMBOX, cropArray);
					pdfDictionary.put(PdfName.BLEEDBOX, cropArray);
				}
			}
			return filename;
		} finally {
			stamper.close();
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw e;
	} finally {
		reader.close();
	}
}
 
Example #29
Source File: PdfSurveyServices.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 */
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
    Map<String, Object> acroFieldMap = new HashMap<>();
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Delegator delegator = dctx.getDelegator();
        ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
        PdfReader r = new PdfReader(byteBuffer.array());
        PdfStamper s = new PdfStamper(r,os);
        AcroFields fs = s.getAcroFields();
        Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
        s.setFormFlattening(true);

        for (String fieldName : map.keySet()) {
            String parmValue = fs.getField(fieldName);
            acroFieldMap.put(fieldName, parmValue);
        }

    } catch (DocumentException | GeneralException | IOException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("acroFieldMap", acroFieldMap);
return results;
}
 
Example #30
Source File: PdfJCacheInformationsReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void writeHeader() throws DocumentException {
	final List<String> headers = createHeaders();
	final int[] relativeWidths = new int[headers.size()];
	Arrays.fill(relativeWidths, 0, headers.size(), 4);
	relativeWidths[headers.size() - 1] = 1;
	initTable(headers, relativeWidths);
}