Java Examples for org.apache.pdfbox.pdmodel.font.PDFont
The following java examples will help you to understand the usage of org.apache.pdfbox.pdmodel.font.PDFont. These source code samples are taken from different open source projects.
Example 1
| Project: OpenLegislation-master File: TranscriptPdfView.java View source code |
public static void writeTranscriptPdf(Transcript transcript, OutputStream outputStream) throws IOException, COSVisitorException {
if (transcript == null) {
throw new IllegalArgumentException("Supplied transcript cannot be null when converting to pdf.");
}
try (PDDocument doc = new PDDocument()) {
PDFont font = PDType1Font.COURIER;
List<List<String>> pages = TranscriptTextUtils.getPdfFormattedPages(transcript.getText());
for (List<String> page : pages) {
PDPage pg = new PDPage(PDPage.PAGE_SIZE_LETTER);
PDPageContentStream contentStream = new PDPageContentStream(doc, pg);
drawBorder(contentStream);
contentStream.beginText();
contentStream.setFont(font, fontSize);
moveStreamToTopOfPage(contentStream);
int lineCount = drawPageText(page, contentStream);
drawStenographer(transcript, contentStream, lineCount);
contentStream.endText();
contentStream.close();
doc.addPage(pg);
}
doc.save(outputStream);
}
}Example 2
| Project: pdfbox-master File: PDDocument.java View source code |
/**
* This will save the document to an output stream.
*
* @param output The stream to write to. It is recommended to wrap it in a
* {@link java.io.BufferedOutputStream}, unless it is already buffered.
*
* @throws IOException if the output could not be written
*/
public void save(OutputStream output) throws IOException {
if (document.isClosed()) {
throw new IOException("Cannot save a document which has been closed");
}
// subset designated fonts
for (PDFont font : fontsToSubset) {
font.subset();
}
fontsToSubset.clear();
// save PDF
try (COSWriter writer = new COSWriter(output)) {
writer.write(this);
}
}Example 3
| Project: brigen-base-master File: TextPagesAppender.java View source code |
@Override
protected void appendContent(int end, int start, int pages, int page, PDPageContentStream contentStream, PDRectangle rect) throws IOException {
PDFont font = getFont();
float fontSize = getFontSize();
contentStream.beginText();
contentStream.setFont(font, fontSize);
contentStream.setNonStrokingColor(getColor());
String str = getText(end, start, pages, page);
float contentWidth;
float contentHeight;
{
contentWidth = (font.getStringWidth(str) / 1000) * fontSize;
contentHeight = (font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000) * fontSize;
}
double angle = (getRotate() * Math.PI) / 180.0;
float[] point = getRotatePoint(angle, rect.getWidth(), rect.getHeight(), contentWidth, contentHeight);
contentStream.setTextRotation(angle, point[0], point[1]);
contentStream.drawString(str);
contentStream.endText();
}Example 4
| Project: PDF-to-unusual-HTML-master File: PDPageContentStream.java View source code |
/**
* Set the font to draw text with.
*
* @param font The font to use.
* @param fontSize The font size to draw the text.
* @throws IOException If there is an error writing the font information.
*/
public void setFont(PDFont font, float fontSize) throws IOException {
String fontMapping = fontMappings.get(font);
if (fontMapping == null) {
fontMapping = MapUtil.getNextUniqueKey(fonts, "F");
fontMappings.put(font, fontMapping);
fonts.put(fontMapping, font);
}
appendRawCommands("/");
appendRawCommands(fontMapping);
appendRawCommands(SPACE);
appendRawCommands(formatDecimal.format(fontSize));
appendRawCommands(SPACE);
appendRawCommands(SET_FONT);
}Example 5
| Project: with-aes-master File: PDPageContentStream.java View source code |
/**
* Set the font to draw text with.
*
* @param font The font to use.
* @param fontSize The font size to draw the text.
* @throws IOException If there is an error writing the font information.
*/
public void setFont(PDFont font, float fontSize) throws IOException {
String fontMapping = fontMappings.get(font);
if (fontMapping == null) {
fontMapping = MapUtil.getNextUniqueKey(fonts, "F");
fontMappings.put(font, fontMapping);
fonts.put(fontMapping, font);
}
appendRawCommands("/");
appendRawCommands(fontMapping);
appendRawCommands(SPACE);
appendRawCommands(formatDecimal.format(fontSize));
appendRawCommands(SPACE);
appendRawCommands(SET_FONT);
}Example 6
| Project: nuxeo-versions-difference-master File: TestPdfBoxN.java View source code |
public void create(String message, String outfile) throws IOException, COSVisitorException {
PDDocument doc = null;
try {
doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
PDFont font = PDType1Font.HELVETICA;
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(100, 700);
contentStream.drawString(message);
contentStream.endText();
contentStream.close();
doc.save(outfile);
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 7
| Project: CZ3003_Backend-master File: CReport.java View source code |
public static void genReport(JSONArray pObjAry) throws IOException, COSVisitorException {
String imagePath = "C:\\Users\\Bryden\\Desktop\\pie-sample.png";
List<List<String>> lstContents = new ArrayList<>();
List<String> aryLst = new ArrayList<>();
aryLst.add("Incident Type");
aryLst.add("");
lstContents.add(aryLst);
for (Object obj : pObjAry) {
JSONObject objJson = (JSONObject) obj;
Iterator<?> keys = objJson.keySet().iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
// loop to get the dynamic key
String value = (String) objJson.get(key);
List<String> aryValues = new ArrayList<>();
aryValues.add(key);
aryValues.add(value);
lstContents.add(aryValues);
}
}
try (// Create a document and add a page to it
PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
InputStream in = Files.newInputStream(Paths.get(imagePath));
PDJpeg img = new PDJpeg(document, in);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
try (// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.beginText();
contentStream.setFont(font, 20);
contentStream.moveTextPositionByAmount(70, 720);
contentStream.drawString("Incident Summary " + new Date());
contentStream.endText();
contentStream.beginText();
contentStream.setFont(font, 20);
contentStream.moveTextPositionByAmount(100, 670);
contentStream.drawString("Statistics");
contentStream.endText();
contentStream.drawImage(img, 10, 10);
drawTable(page, contentStream, 650, 100, lstContents);
// Make sure that the content stream is closed:
}
img.clear();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
}
}Example 8
| Project: gcs-master File: PdfRenderer.java View source code |
@Override
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
text = text.toLowerCase();
int index = text.indexOf(mTextToHighlight);
if (index != -1) {
PDPage currentPage = getCurrentPage();
PDRectangle pageBoundingBox = currentPage.getBBox();
AffineTransform flip = new AffineTransform();
flip.translate(0, pageBoundingBox.getHeight());
flip.scale(1, -1);
PDRectangle mediaBox = currentPage.getMediaBox();
float mediaHeight = mediaBox.getHeight();
float mediaWidth = mediaBox.getWidth();
int size = textPositions.size();
while (index != -1) {
int last = index + mTextToHighlight.length() - 1;
for (int i = index; i <= last; i++) {
TextPosition pos = textPositions.get(i);
PDFont font = pos.getFont();
BoundingBox bbox = font.getBoundingBox();
Rectangle2D.Float rect = new Rectangle2D.Float(0, bbox.getLowerLeftY(), font.getWidth(pos.getCharacterCodes()[0]), bbox.getHeight());
AffineTransform at = pos.getTextMatrix().createAffineTransform();
if (font instanceof PDType3Font) {
at.concatenate(font.getFontMatrix().createAffineTransform());
} else {
at.scale(1 / 1000f, 1 / 1000f);
}
Shape shape = flip.createTransformedShape(at.createTransformedShape(rect));
AffineTransform transform = mGC.getTransform();
int rotation = currentPage.getRotation();
if (rotation != 0) {
switch(rotation) {
case 90:
mGC.translate(mediaHeight, 0);
break;
case 270:
mGC.translate(0, mediaWidth);
break;
case 180:
mGC.translate(mediaWidth, mediaHeight);
break;
default:
break;
}
mGC.rotate(Math.toRadians(rotation));
}
mGC.fill(shape);
if (rotation != 0) {
mGC.setTransform(transform);
}
}
index = last < size - 1 ? text.indexOf(mTextToHighlight, last + 1) : -1;
}
}
}Example 9
| Project: padaf-master File: Type3FontValidator.java View source code |
/**
* If the Resources entry is present, this method check its content. Only
* fonts and Images are checked because this resource describes glyphs. REMARK
* : The font and the image aren't validated because they will be validated by
* an other ValidationHelper.
*
* @return
*/
private boolean checkResources() throws ValidationException {
if (this.resources == null) {
// ---- No resources dictionary.
return true;
}
COSDocument cDoc = this.handler.getDocument().getDocument();
COSDictionary dictionary = COSUtils.getAsDictionary(this.resources, cDoc);
if (dictionary == null) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID, "The Resources element isn't a dictionary"));
return false;
}
COSBase cbImg = dictionary.getItem(COSName.getPDFName(DICTIONARY_KEY_XOBJECT));
COSBase cbFont = dictionary.getItem(COSName.getPDFName(DICTIONARY_KEY_FONT));
if (cbImg == null && cbFont == null) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED, "The Resources element doesn't have Glyph information"));
return false;
}
if (cbImg != null) {
// ---- the referenced objects must be present in the PDF file
COSDictionary dicImgs = COSUtils.getAsDictionary(cbImg, cDoc);
Set<COSName> keyList = dicImgs.keySet();
for (Object key : keyList) {
COSBase item = dictionary.getItem((COSName) key);
COSDictionary xObjImg = COSUtils.getAsDictionary(item, cDoc);
if (xObjImg == null) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID, "The Resources dictionary of type 3 font is invalid"));
return false;
}
if (!XOBJECT_DICTIONARY_VALUE_SUBTYPE_IMG.equals(xObjImg.getString(COSName.getPDFName(DICTIONARY_KEY_SUBTYPE)))) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID, "The Resources dictionary of type 3 font is invalid"));
return false;
}
}
}
if (cbFont != null) {
// ---- the referenced object must be present in the PDF file
COSDictionary dicFonts = COSUtils.getAsDictionary(cbFont, cDoc);
Set<COSName> keyList = dicFonts.keySet();
for (Object key : keyList) {
COSBase item = dictionary.getItem((COSName) key);
COSDictionary xObjFont = COSUtils.getAsDictionary(item, cDoc);
if (xObjFont == null) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID, "The Resources dictionary of type 3 font is invalid"));
return false;
}
if (!FONT_DICTIONARY_VALUE_FONT.equals(xObjFont.getString(COSName.getPDFName(DICTIONARY_KEY_TYPE)))) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID, "The Resources dictionary of type 3 font is invalid"));
return false;
}
try {
PDFont aFont = PDFontFactory.createFont(xObjFont);
// FontContainer aContainer = this.handler.retrieveFontContainer(aFont);
AbstractFontContainer aContainer = this.handler.getFont(aFont.getCOSObject());
// ---- another font is used in the Type3, check if the font is valid.
if (aContainer.isValid() != State.VALID) {
this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED, "The Resources dictionary of type 3 font contains invalid font"));
return false;
}
} catch (IOException e) {
throw new ValidationException("Unable to valid the Type3 : " + e.getMessage());
}
}
}
List<ValidationError> errors = new ArrayList<ValidationError>();
ExtGStateContainer extGStates = new ExtGStateContainer(dictionary, cDoc);
boolean res = extGStates.validateTransparencyRules(errors);
for (ValidationError err : errors) {
this.fontContainer.addError(err);
}
return res && validateShadingPattern(dictionary, errors);
}Example 10
| Project: PDFExtract-master File: PDFBoxIntegration.java View source code |
/**
* Old version
*/
public void processEncodedText(@NotNull byte[] string) throws IOException {
/*
* Note on variable names. There are three different units being used
* in this code. Character sizes are given in glyph units, text locations
* are initially given in text units, and we want to save the data in
* display units. The variable names should end with Text or Disp to
* represent if the values are in text or disp units (no glyph units are saved).
*/
final float fontSizeText = getGraphicsState().getTextState().getFontSize();
final float horizontalScalingText = getGraphicsState().getTextState().getHorizontalScalingPercent() / 100f;
// float verticalScalingText = horizontalScaling;//not sure if this is right but what else to
// do???
final float riseText = getGraphicsState().getTextState().getRise();
final float wordSpacingText = getGraphicsState().getTextState().getWordSpacing();
final float characterSpacingText = getGraphicsState().getTextState().getCharacterSpacing();
/*
* We won't know the actual number of characters until
* we process the byte data(could be two bytes each) but
* it won't ever be more than string.length*2(there are some cases
* were a single byte will result in two output characters "fi"
*/
final PDFont font = getGraphicsState().getTextState().getFont();
/*
* This will typically be 1000 but in the case of a type3 font this might be a different
* number
*/
final float glyphSpaceToTextSpaceFactor;
if (font instanceof PDType3Font) {
PDMatrix fontMatrix = font.getFontMatrix();
float fontMatrixXScaling = fontMatrix.getValue(0, 0);
glyphSpaceToTextSpaceFactor = 1.0f / fontMatrixXScaling;
} else {
glyphSpaceToTextSpaceFactor = /* 1.0f / */
1000f;
}
float spaceWidthText = 0.0F;
try {
spaceWidthText = (font.getFontWidth(SPACE_BYTES, 0, 1) / glyphSpaceToTextSpaceFactor);
} catch (Throwable exception) {
log.warn(exception, exception);
}
if (spaceWidthText == 0.0F) {
spaceWidthText = (font.getAverageFontWidth() / glyphSpaceToTextSpaceFactor);
spaceWidthText *= .80f;
}
/* Convert textMatrix to display units */
final Matrix initialMatrix = new Matrix();
initialMatrix.setValue(0, 0, 1.0F);
initialMatrix.setValue(0, 1, 0.0F);
initialMatrix.setValue(0, 2, 0.0F);
initialMatrix.setValue(1, 0, 0.0F);
initialMatrix.setValue(1, 1, 1.0F);
initialMatrix.setValue(1, 2, 0.0F);
initialMatrix.setValue(2, 0, 0.0F);
initialMatrix.setValue(2, 1, riseText);
initialMatrix.setValue(2, 2, 1.0F);
final Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
final Matrix dispMatrix = initialMatrix.multiply(ctm);
Matrix textMatrixStDisp = getTextMatrix().multiply(dispMatrix);
final float xScaleDisp = textMatrixStDisp.getXScale();
final float yScaleDisp = textMatrixStDisp.getYScale();
final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText;
final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText;
float maxVerticalDisplacementText = 0.0F;
StringBuilder characterBuffer = new StringBuilder(string.length);
int codeLength = 1;
for (int i = 0; i < string.length; i += codeLength) {
// Decode the value to a Unicode character
codeLength = 1;
String c = font.encode(string, i, codeLength);
if ((c == null) && (i + 1 < string.length)) {
// maybe a multibyte encoding
codeLength++;
c = font.encode(string, i, codeLength);
}
c = inspectFontEncoding(c);
// todo, handle horizontal displacement
// get the width and height of this character in text units
float fontWidth = font.getFontWidth(string, i, codeLength) * 0.95f;
if (fontWidth == 0.0f) {
fontWidth = spaceWidthDisp;
}
float characterHorizontalDisplacementText = (fontWidth / glyphSpaceToTextSpaceFactor);
maxVerticalDisplacementText = Math.max(maxVerticalDisplacementText, font.getFontHeight(string, i, codeLength) / glyphSpaceToTextSpaceFactor);
if (maxVerticalDisplacementText <= 0.0f) {
maxVerticalDisplacementText = font.getFontBoundingBox().getHeight() / glyphSpaceToTextSpaceFactor;
}
/**
* PDF Spec - 5.5.2 Word Spacing
*
* Word spacing works the same was as character spacing, but applies
* only to the space character, code 32.
*
* Note: Word spacing is applied to every occurrence of the single-byte
* character code 32 in a string. This can occur when using a simple
* font or a composite font that defines code 32 as a single-byte code.
* It does not apply to occurrences of the byte value 32 in multiple-byte
* codes.
*
* RDD - My interpretation of this is that only character code 32's that
* encode to spaces should have word spacing applied. Cases have been
* observed where a font has a space character with a character code
* other than 32, and where word spacing (Tw) was used. In these cases,
* applying word spacing to either the non-32 space or to the character
* code 32 non-space resulted in errors consistent with this interpretation.
*/
float spacingText = characterSpacingText;
if ((string[i] == (byte) 0x20) && (codeLength == 1)) {
spacingText += wordSpacingText;
}
/*
* The text matrix gets updated after each glyph is placed. The updated
* version will have the X and Y coordinates for the next glyph.
*/
Matrix glyphMatrixStDisp = getTextMatrix().multiply(dispMatrix);
// The adjustment will always be zero. The adjustment as shown in the
// TJ operator will be handled separately.
float adjustment = 0.0F;
// TODO : tx should be set for horizontal text and ty for vertical text
// which seems to be specified in the font (not the direction in the matrix).
float tx = ((characterHorizontalDisplacementText - adjustment / glyphSpaceToTextSpaceFactor) * fontSizeText) * horizontalScalingText;
Matrix td = new Matrix();
td.setValue(2, 0, tx);
float ty = 0.0F;
td.setValue(2, 1, ty);
setTextMatrix(td.multiply(getTextMatrix()));
Matrix glyphMatrixEndDisp = getTextMatrix().multiply(dispMatrix);
float sx = spacingText * horizontalScalingText;
Matrix sd = new Matrix();
sd.setValue(2, 0, sx);
float sy = 0.0F;
sd.setValue(2, 1, sy);
setTextMatrix(sd.multiply(getTextMatrix()));
float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition();
characterBuffer.append(c);
Matrix textMatrixEndDisp = glyphMatrixEndDisp;
float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp;
try {
final ETextPosition text = new ETextPosition(page, textMatrixStDisp, textMatrixEndDisp, totalVerticalDisplacementDisp, new float[] { widthText }, spaceWidthDisp, characterBuffer.toString(), font, fontSizeText, (int) (fontSizeText * getTextMatrix().getXScale()), wordSpacingDisp);
correctPosition(font, string, i, c, fontSizeText, glyphSpaceToTextSpaceFactor, horizontalScalingText, codeLength, text);
processTextPosition(text);
} catch (Exception e) {
log.warn("LOG00570:Error adding '" + characterBuffer + "': " + e.getMessage());
}
textMatrixStDisp = getTextMatrix().multiply(dispMatrix);
characterBuffer.setLength(0);
}
}Example 11
| Project: amos-ss15-proj4-master File: ZipGenerator.java View source code |
public void generate(OutputStream out, Locale locale, float height, Employee employee, int fontSize, String zipPassword) throws ZipException, NoSuchMessageException, IOException, COSVisitorException, CloneNotSupportedException {
final ZipOutputStream zout = new ZipOutputStream(out);
if (zipPassword == null) {
// Use default password if none is set.
zipPassword = "fragebogen";
}
ZipParameters params = new ZipParameters();
params.setFileNameInZip("employee.txt");
params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE);
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
params.setEncryptFiles(true);
params.setReadHiddenFiles(false);
params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
params.setPassword(zipPassword);
params.setSourceExternalStream(true);
zout.putNextEntry(null, params);
zout.write((AppContext.getApplicationContext().getMessage("HEADER", null, locale) + "\n\n").getBytes());
zout.write((AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale) + "\n\n").getBytes());
Iterator it = employee.getPersonalDataFields().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
// avoids a ConcurrentModificationException
it.remove();
}
zout.write(("\n\n" + AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale) + "\n\n").getBytes());
it = employee.getTaxesFields().entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
// avoids a ConcurrentModificationException
it.remove();
}
zout.closeEntry();
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
float y = -1;
int margin = 100;
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.TIMES_ROMAN;
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.beginText();
y = page.getMediaBox().getHeight() - margin + height;
contentStream.moveTextPositionByAmount(margin, y);
/*
List<String> list = StringUtils.splitEqually(fileContent, 90);
for (String e : list) {
contentStream.moveTextPositionByAmount(0, -15);
contentStream.drawString(e);
}
*/
contentStream.setFont(PDType1Font.TIMES_BOLD, 36);
contentStream.drawString(AppContext.getApplicationContext().getMessage("HEADER", null, locale));
contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
contentStream.moveTextPositionByAmount(0, -4 * height);
contentStream.drawString(AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale));
contentStream.moveTextPositionByAmount(0, -2 * height);
contentStream.setFont(font, fontSize);
it = employee.getPersonalDataFields().entrySet().iterator();
while (it.hasNext()) {
StringBuffer nextLineToDraw = new StringBuffer();
Map.Entry pair = (Map.Entry) it.next();
nextLineToDraw.append(pair.getKey());
nextLineToDraw.append(": ");
nextLineToDraw.append(pair.getValue());
contentStream.drawString(nextLineToDraw.toString());
contentStream.moveTextPositionByAmount(0, -height);
// avoids a ConcurrentModificationException
it.remove();
}
contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
contentStream.moveTextPositionByAmount(0, -2 * height);
contentStream.drawString(AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale));
contentStream.moveTextPositionByAmount(0, -2 * height);
contentStream.setFont(font, fontSize);
it = employee.getTaxesFields().entrySet().iterator();
while (it.hasNext()) {
StringBuffer nextLineToDraw = new StringBuffer();
Map.Entry pair = (Map.Entry) it.next();
nextLineToDraw.append(pair.getKey());
nextLineToDraw.append(": ");
nextLineToDraw.append(pair.getValue());
contentStream.drawString(nextLineToDraw.toString());
contentStream.moveTextPositionByAmount(0, -height);
// avoids a ConcurrentModificationException
it.remove();
}
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
ByteArrayOutputStream pdfout = new ByteArrayOutputStream();
document.save(pdfout);
document.close();
ZipParameters params2 = (ZipParameters) params.clone();
params2.setFileNameInZip("employee.pdf");
zout.putNextEntry(null, params2);
zout.write(pdfout.toByteArray());
zout.closeEntry();
// Write the zip to client
zout.finish();
zout.flush();
zout.close();
}Example 12
| Project: elexis-3-base-master File: PrintVaccinationEntriesHandler.java View source code |
private void createPDF(Patient patient, Image image) throws IOException, COSVisitorException {
PDDocumentInformation pdi = new PDDocumentInformation();
Mandant mandant = (Mandant) ElexisEventDispatcher.getSelected(Mandant.class);
pdi.setAuthor(mandant.getName() + " " + mandant.getVorname());
pdi.setCreationDate(new GregorianCalendar());
pdi.setTitle("Impfausweis " + patient.getLabel());
PDDocument document = new PDDocument();
document.setDocumentInformation(pdi);
PDPage page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
document.addPage(page);
PDRectangle pageSize = page.findMediaBox();
PDFont font = PDType1Font.HELVETICA_BOLD;
PDFont subFont = PDType1Font.HELVETICA;
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.setFont(font, 14);
contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 40);
contentStream.drawString(patient.getLabel());
contentStream.endText();
String dateLabel = sdf.format(Calendar.getInstance().getTime());
String title = Person.load(mandant.getId()).get(Person.TITLE);
String mandantLabel = title + " " + mandant.getName() + " " + mandant.getVorname();
contentStream.beginText();
contentStream.setFont(subFont, 10);
contentStream.moveTextPositionByAmount(40, pageSize.getUpperRightY() - 55);
contentStream.drawString("Ausstellung " + dateLabel + ", " + mandantLabel);
contentStream.endText();
BufferedImage imageAwt = convertToAWT(image.getImageData());
PDXObjectImage pdPixelMap = new PDPixelMap(document, imageAwt);
contentStream.drawXObject(pdPixelMap, 40, 30, pageSize.getWidth() - 80, pageSize.getHeight() - 100);
contentStream.close();
String outputPath = CoreHub.userCfg.get(PreferencePage.VAC_PDF_OUTPUTDIR, CoreHub.getWritableUserDir().getAbsolutePath());
if (outputPath.equals(CoreHub.getWritableUserDir().getAbsolutePath())) {
SWTHelper.showInfo("Kein Ausgabeverzeichnis definiert", "Ausgabe erfolgt in: " + outputPath + "\nDas Ausgabeverzeichnis kann unter Einstellungen\\Klinische Hilfsmittel\\Impfplan definiert werden.");
}
File outputDir = new File(outputPath);
File pdf = new File(outputDir, "impfplan_" + patient.getPatCode() + ".pdf");
document.save(pdf);
document.close();
Desktop.getDesktop().open(pdf);
}Example 13
| Project: is.idega.idegaweb.marathon-master File: PDFTester.java View source code |
public void doIt(String message, String outfile) throws IOException, COSVisitorException {
// the document
PDDocument doc = null;
try {
doc = new PDDocument();
// Page 1
PDFont font = PDType1Font.HELVETICA;
PDPage page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
float fontSize = 12.0f;
PDRectangle pageSize = page.findMediaBox();
float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f;
float stringWidth = font.getStringWidth(message);
float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f;
PDPageContentStream contentStream = new PDPageContentStream(doc, page, false, false);
contentStream.setFont(font, fontSize);
contentStream.beginText();
// counterclockwise rotation
for (int i = 0; i < 8; i++) {
contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition);
contentStream.drawString(message + " " + i);
}
// clockwise rotation
for (int i = 0; i < 8; i++) {
contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition);
contentStream.drawString(message + " " + i);
}
contentStream.endText();
contentStream.close();
// Page 2
page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
fontSize = 1.0f;
contentStream = new PDPageContentStream(doc, page, false, false);
contentStream.setFont(font, fontSize);
contentStream.beginText();
// text scaling
for (int i = 0; i < 10; i++) {
contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50);
contentStream.drawString(message + " " + i);
}
contentStream.endText();
contentStream.close();
// Page 3
page = new PDPage();
page.setMediaBox(PDPage.PAGE_SIZE_A4);
doc.addPage(page);
fontSize = 1.0f;
contentStream = new PDPageContentStream(doc, page, false, false);
contentStream.setFont(font, fontSize);
contentStream.beginText();
int i = 0;
// text scaling combined with rotation
contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5);
contentStream.drawString(message + " " + i++);
contentStream.endText();
contentStream.close();
doc.save(outfile);
} finally {
if (doc != null) {
doc.close();
}
}
}Example 14
| Project: openolat-master File: PdfDocument.java View source code |
public void addParagraph(String text, float fontSize, boolean bold, float width) throws IOException {
float leading = lineHeightFactory * fontSize;
PDFont textFont = bold ? fontBold : font;
List<String> lines = new ArrayList<String>();
int lastSpace = -1;
while (text.length() > 0) {
int spaceIndex = text.indexOf(' ', lastSpace + 1);
if (spaceIndex < 0) {
lines.add(text);
text = "";
} else {
String subString = text.substring(0, spaceIndex);
float size = fontSize * textFont.getStringWidth(subString) / 1000;
if (size > width) {
if (// So we have a word longer than the line... draw it anyways
lastSpace < 0)
lastSpace = spaceIndex;
subString = text.substring(0, lastSpace);
lines.add(subString);
text = text.substring(lastSpace).trim();
lastSpace = -1;
} else {
lastSpace = spaceIndex;
}
}
}
currentContentStream.beginText();
currentContentStream.setFont(textFont, fontSize);
currentContentStream.moveTextPositionByAmount(marginLeftRight, currentY);
for (String line : lines) {
currentContentStream.drawString(line);
currentContentStream.moveTextPositionByAmount(0, -leading);
currentY -= leading;
}
currentContentStream.endText();
}Example 15
| Project: com.revolsys.open-master File: PdfViewport.java View source code |
@Override
public void drawText(final Record record, final Geometry geometry, final TextStyle style) {
try {
final String label = TextStyleRenderer.getLabel(record, style);
if (Property.hasValue(label) && geometry != null) {
final String textPlacementType = style.getTextPlacementType();
final PointDoubleXYOrientation point = AbstractRecordLayerRenderer.getPointWithOrientation(this, geometry, textPlacementType);
if (point != null) {
final double orientation = point.getOrientation();
this.contentStream.saveGraphicsState();
try {
// style.setTextStyle(viewport, graphics);
final double x = point.getX();
final double y = point.getY();
final double[] location = toViewCoordinates(x, y);
// style.setTextStyle(viewport, graphics);
final Measure<Length> textDx = style.getTextDx();
double dx = Viewport2D.toDisplayValue(this, textDx);
final Measure<Length> textDy = style.getTextDy();
double dy = -Viewport2D.toDisplayValue(this, textDy);
final Font font = style.getFont(this);
final FontMetrics fontMetrics = this.canvas.getFontMetrics(font);
double maxWidth = 0;
final String[] lines = label.split("[\\r\\n]");
for (final String line : lines) {
final Rectangle2D bounds = fontMetrics.getStringBounds(line, this.canvas.getGraphics());
final double width = bounds.getWidth();
maxWidth = Math.max(width, maxWidth);
}
final int descent = fontMetrics.getDescent();
final int ascent = fontMetrics.getAscent();
final int leading = fontMetrics.getLeading();
final double maxHeight = lines.length * (ascent + descent) + (lines.length - 1) * leading;
final String verticalAlignment = style.getTextVerticalAlignment();
if ("top".equals(verticalAlignment)) {
} else if ("middle".equals(verticalAlignment)) {
dy -= maxHeight / 2;
} else {
dy -= maxHeight;
}
String horizontalAlignment = style.getTextHorizontalAlignment();
double screenX = location[0];
double screenY = getViewHeightPixels() - location[1];
final String textPlacement = style.getTextPlacementType();
if ("auto".equals(textPlacement)) {
if (screenX < 0) {
screenX = 1;
dx = 0;
horizontalAlignment = "left";
}
final int viewWidth = getViewWidthPixels();
if (screenX + maxWidth > viewWidth) {
screenX = (int) (viewWidth - maxWidth - 1);
dx = 0;
horizontalAlignment = "left";
}
if (screenY < maxHeight) {
screenY = 1;
dy = 0;
}
final int viewHeight = getViewHeightPixels();
if (screenY > viewHeight) {
screenY = viewHeight - 1 - maxHeight;
dy = 0;
}
}
AffineTransform transform = new AffineTransform();
transform.translate(screenX, screenY);
if (orientation != 0) {
transform.rotate(-Math.toRadians(orientation), 0, 0);
}
transform.translate(dx, dy);
for (final String line : lines) {
transform.translate(0, ascent);
final AffineTransform lineTransform = new AffineTransform(transform);
final Rectangle2D bounds = fontMetrics.getStringBounds(line, this.canvas.getGraphics());
final double width = bounds.getWidth();
final double height = bounds.getHeight();
if ("right".equals(horizontalAlignment)) {
transform.translate(-width, 0);
} else if ("center".equals(horizontalAlignment)) {
transform.translate(-width / 2, 0);
}
transform.translate(dx, 0);
transform.scale(1, 1);
if (Math.abs(orientation) > 90) {
transform.rotate(Math.PI, maxWidth / 2, -height / 4);
}
/*
* final double textHaloRadius = Viewport2D.toDisplayValue(this,
* style.getTextHaloRadius()); if (textHaloRadius > 0) {
* graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
* RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); final Stroke savedStroke =
* graphics.getStroke(); final Stroke outlineStroke = new BasicStroke(
* (float)textHaloRadius, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);
* graphics.setColor(style.getTextHaloFill()); graphics.setStroke(outlineStroke);
* final Font font = graphics.getFont(); final FontRenderContext fontRenderContext =
* graphics.getFontRenderContext(); final TextLayout textLayout = new TextLayout(line,
* font, fontRenderContext); final Shape outlineShape =
* textLayout.getOutline(TextStyleRenderer.NOOP_TRANSFORM);
* graphics.draw(outlineShape); graphics.setStroke(savedStroke); }
*/
final Color textBoxColor = style.getTextBoxColor();
if (textBoxColor != null) {
this.contentStream.setNonStrokingColor(textBoxColor);
final double cornerSize = Math.max(height / 2, 5);
// final RoundRectangle2D.Double box = new
// RoundRectangle2D.Double(
// bounds.getX() - 3, bounds.getY() - 1, width + 6, height + 2,
// cornerSize, cornerSize);
this.contentStream.fillRect((float) bounds.getX() - 3, (float) bounds.getY() - 1, (float) width + 6, (float) height + 2);
}
this.contentStream.setNonStrokingColor(style.getTextFill());
this.contentStream.beginText();
final PDFont pdfFont = getFont("/org/apache/pdfbox/resources/ttf/ArialMT.ttf");
this.contentStream.setFont(pdfFont, font.getSize2D());
this.contentStream.setTextMatrix(transform);
this.contentStream.drawString(line);
this.contentStream.endText();
transform = lineTransform;
transform.translate(0, leading + descent);
}
} finally {
this.contentStream.restoreGraphicsState();
}
}
}
} catch (final IOException e) {
throw new RuntimeException("Unable to write PDF", e);
}
}Example 16
| Project: DSpace-master File: CitationDocumentServiceImpl.java View source code |
protected void generateCoverPage(Context context, PDDocument document, PDPage coverPage, Item item) throws IOException {
PDPageContentStream contentStream = new PDPageContentStream(document, coverPage);
try {
int ypos = 760;
int xpos = 30;
int xwidth = 550;
int ygap = 20;
PDFont fontHelvetica = PDType1Font.HELVETICA;
PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
PDFont fontHelveticaOblique = PDType1Font.HELVETICA_OBLIQUE;
contentStream.setNonStrokingColor(Color.BLACK);
String[][] content = { header1 };
drawTable(coverPage, contentStream, ypos, xpos, content, fontHelveticaBold, 11, false);
ypos -= (ygap);
String[][] content2 = { header2 };
drawTable(coverPage, contentStream, ypos, xpos, content2, fontHelveticaBold, 11, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
String[][] content3 = { { getOwningCommunity(context, item), getOwningCollection(item) } };
drawTable(coverPage, contentStream, ypos, xpos, content3, fontHelvetica, 9, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap * 2);
for (String field : fields) {
field = field.trim();
PDFont font = fontHelvetica;
int fontSize = 11;
if (field.contains("title")) {
fontSize = 26;
ypos -= ygap;
} else if (field.contains("creator") || field.contains("contributor")) {
fontSize = 16;
}
if (field.equals("_line_")) {
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap);
} else if (StringUtils.isNotEmpty(itemService.getMetadata(item, field))) {
ypos = drawStringWordWrap(coverPage, contentStream, itemService.getMetadata(item, field), xpos, ypos, font, fontSize);
}
if (field.contains("title")) {
ypos -= ygap;
}
}
contentStream.beginText();
contentStream.setFont(fontHelveticaOblique, 11);
contentStream.moveTextPositionByAmount(xpos, ypos);
contentStream.drawString(footer);
contentStream.endText();
} finally {
contentStream.close();
}
}Example 17
| Project: flaming-sailor-master File: PDFParser.java View source code |
@Override
protected void endPage(PDPage page) throws IOException {
super.endPage(page);
int pieceID = 0;
Map<String, Map<Integer, Long>> fontCounts = new HashMap<>();
List<TextPiece> wordsOfThisPage = new ArrayList<>();
for (List<TextPosition> aCharactersByArticle : charactersByArticle) {
// int len = aCharactersByArticle.size();
for (TextPosition t : aCharactersByArticle) {
// copy information
TextPiece w = new TextPiece(pieceID++);
PDFont font = t.getFont();
PDFontDescriptor fontDescriptor = font.getFontDescriptor();
// w.setFontDescriptor(fontDescriptor);
if (fontDescriptor == null) {
w.setFontName("UNKNOWN");
} else {
w.setFontName(fontDescriptor.getFontName());
}
/*
* 100: a simple step to fix the font size to the normal range, for those documents in unknown codes that PDFBox can not process now
*/
if (t.getFontSize() < 0.3 && t.getYScale() <= 1.0) {
w.setFontSize(t.getFontSize() * 100);
w.setHeight(Math.max(t.getYScale(), t.getFontSize()) * 100);
w.setXScale(t.getXScale());
w.setYScale(t.getYScale());
} else {
if (t.getYScale() < 0.3 && t.getFontSize() <= 1.0) {
w.setYScale(t.getYScale() * 100);
w.setXScale(t.getXScale() * 100);
w.setHeight(Math.max(t.getYScale() * 100, t.getFontSize()));
} else {
w.setFontSize(t.getFontSize());
w.setHeight(Math.max(t.getYScale(), t.getFontSize()));
w.setXScale(t.getXScale());
w.setYScale(t.getYScale());
}
}
Map<Integer, Long> counts = fontCounts.get(w.getFontName());
if (counts == null) {
counts = new HashMap<>();
fontCounts.put(w.getFontName(), counts);
}
Long count = counts.get((int) Math.round(w.getHeight()));
if (count == null) {
count = 1L;
} else {
count += 1L;
}
counts.put((int) Math.round(w.getHeight()), count);
w.setWidth(Math.abs(t.getWidth()));
w.setGeom(t.getX(), t.getY(), w.getWidth(), w.getHeight());
w.setText(t.getCharacter());
w.setWidthOfSpace(t.getWidthOfSpace());
wordsOfThisPage.add(w);
}
}
currentPage.processPage(wordsOfThisPage, fontCounts);
currentPage.setText(outString.getBuffer().toString());
outString.getBuffer().setLength(0);
List<PDAnnotation> annotations = page.getAnnotations();
for (PDAnnotation annotation : annotations) {
if (annotation instanceof PDAnnotationLink) {
PDAnnotationLink l = (PDAnnotationLink) annotation;
PDRectangle rect = l.getRectangle();
PDDestination dest = l.getDestination();
if (dest instanceof PDPageXYZDestination) {
PDPageXYZDestination xyzDestination = (PDPageXYZDestination) dest;
PDPage pageDest = ((PDPageXYZDestination) dest).getPage();
if (rect != null) {
if (xyzDestination.getPageNumber() < 0) {
int pageNumber = allpages.indexOf(pageDest) + 1;
Rectangle2D hotbox = new Rectangle2D.Double(rect.getLowerLeftX(), rect.getLowerLeftY(), (rect.getUpperRightX() - rect.getLowerLeftX()), (rect.getUpperRightY() - rect.getLowerLeftY()));
Point2D toPoint = new Point2D.Double(xyzDestination.getLeft(), xyzDestination.getTop());
currentPage.addLink(new PDLink(hotbox, pageNumber, toPoint));
}
}
}
}
}
/*
The following code is REALLY raw.
initial testing seemed to show memory leaks, and was REALLY slow.
PDResources r = page.getResources();
Map<String, PDXObjectImage> images = r.getImages();
for (Map.Entry<String, PDXObjectImage> e : images.entrySet()) {
BufferedImage bi = null;
try {
// currentPage.addImage(bi);
// (e.getValue()).write2file("/tmp/II" + e.getKey());
if (e.getValue() instanceof PDJpeg) {
PDJpeg jpg = (PDJpeg) e.getValue();
bi = jpg.getRGBImage();
ColorSpace cs = bi.getColorModel().getColorSpace();
File jpgFile = new File("/tmp/II" + e.getKey() + ".jpg");
if (cs instanceof ColorSpaceCMYK) {
logger.info("Ignoring image with CMYK color space");
} else {
// ImageIO.write(bi, "jpg", jpgFile);
jpg.write2file("/tmp/II"+ e.getKey());
}
} else {
(e.getValue()).write2file("/tmp/II" + e.getKey());
}
} catch (Exception ee) {
logger.info("can't read image ;-(", ee);
}
}
*/
textPageList.add(currentPage);
currentPage = null;
}Example 18
| Project: yacy_search_server-master File: pdfParser.java View source code |
public static void clean_up_idiotic_PDFParser_font_cache_which_eats_up_tons_of_megabytes() {
// thank you very much, PDFParser hackers, this font cache will occupy >80MB RAM for a single pdf and then stays forever
// AND I DO NOT EVEN NEED A FONT HERE TO PARSE THE TEXT!
// Don't be so ignorant, just google once "PDFParser OutOfMemoryError" to feel the pain.
ResourceCleaner cl = new ResourceCleaner();
cl.clearClassResources("org.apache.pdfbox.cos.COSName");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType1Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDTrueTypeFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType0Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType1AfmPfbFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType3Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDType1CFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDCIDFont");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDCIDFontType0Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDCIDFontType2Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDMMType1Font");
cl.clearClassResources("org.apache.pdfbox.pdmodel.font.PDSimpleFont");
}Example 19
| Project: Canoo-WebTest-master File: PdfBoxPDFPage.java View source code |
public List getFonts() {
final List<PDFBoxPDFFont> fonts = new ArrayList<PDFBoxPDFFont>();
final List pages = getPDFDocument().getDocumentCatalog().getAllPages();
for (final ListIterator iter = pages.listIterator(); iter.hasNext(); ) {
final PDPage page = (PDPage) iter.next();
try {
for (final Iterator fontIterator = page.findResources().getFonts().values().iterator(); fontIterator.hasNext(); ) {
final PDFont font = (PDFont) fontIterator.next();
// nextIndex() because page number start with 1 not 0
fonts.add(new PDFBoxPDFFont(font, iter.nextIndex()));
}
} catch (final IOException e) {
throw new RuntimeException("Failed retrieving the fonts on page " + iter.nextIndex(), e);
}
}
return fonts;
}Example 20
| Project: dlibrary-master File: CitationDocument.java View source code |
private void generateCoverPage(PDDocument document, PDPage coverPage, Item item) throws IOException, COSVisitorException {
PDPageContentStream contentStream = new PDPageContentStream(document, coverPage);
try {
int ypos = 760;
int xpos = 30;
int xwidth = 550;
int ygap = 20;
PDFont fontHelvetica = PDType1Font.HELVETICA;
PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
PDFont fontHelveticaOblique = PDType1Font.HELVETICA_OBLIQUE;
contentStream.setNonStrokingColor(Color.BLACK);
String[][] content = { header1 };
drawTable(coverPage, contentStream, ypos, xpos, content, fontHelveticaBold, 11, false);
ypos -= (ygap);
String[][] content2 = { header2 };
drawTable(coverPage, contentStream, ypos, xpos, content2, fontHelveticaBold, 11, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
String[][] content3 = { { getOwningCommunity(item), getOwningCollection(item) } };
drawTable(coverPage, contentStream, ypos, xpos, content3, fontHelvetica, 9, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap * 2);
for (String field : fields) {
field = field.trim();
PDFont font = fontHelvetica;
int fontSize = 11;
if (field.contains("title")) {
fontSize = 26;
ypos -= ygap;
} else if (field.contains("creator") || field.contains("contributor")) {
fontSize = 16;
}
if (field.equals("_line_")) {
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap);
} else if (StringUtils.isNotEmpty(item.getMetadata(field))) {
ypos = drawStringWordWrap(coverPage, contentStream, item.getMetadata(field), xpos, ypos, font, fontSize);
}
if (field.contains("title")) {
ypos -= ygap;
}
}
contentStream.beginText();
contentStream.setFont(fontHelveticaOblique, 11);
contentStream.moveTextPositionByAmount(xpos, ypos);
contentStream.drawString(footer);
contentStream.endText();
} finally {
contentStream.close();
}
}Example 21
| Project: tabula-java-master File: ObjectExtractorStreamEngine.java View source code |
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement) throws IOException {
TextPosition textPosition = getTextPosition(textRenderingMatrix, font, code, unicode, displacement);
if (textPosition != null) {
String c = textPosition.getUnicode();
// if c not printable, return
if (!isPrintable(c)) {
return;
}
Float h = textPosition.getHeightDir();
if (c.equals(NBSP)) {
// replace non-breaking space for space
c = " ";
}
float wos = textPosition.getWidthOfSpace();
TextElement te = new TextElement(Utils.round(textPosition.getYDirAdj() - h, 2), Utils.round(textPosition.getXDirAdj(), 2), Utils.round(textPosition.getWidthDirAdj(), 2), Utils.round(textPosition.getHeightDir(), 2), textPosition.getFont(), textPosition.getFontSize(), c, // https://issues.apache.org/jira/browse/PDFBOX-1755
wos, textPosition.getDir());
if (this.currentClippingPath().intersects(te)) {
this.minCharWidth = (float) Math.min(this.minCharWidth, te.getWidth());
this.minCharHeight = (float) Math.min(this.minCharHeight, te.getHeight());
this.spatialIndex.add(te);
this.characters.add(te);
}
if (this.isDebugClippingPaths() && !this.clippingPaths.contains(this.currentClippingPath())) {
this.clippingPaths.add(this.currentClippingPath());
}
}
}Example 22
| Project: vtechworks-master File: CitationDocument.java View source code |
private void generateCoverPage(PDDocument document, PDPage coverPage, Item item) throws IOException, COSVisitorException {
PDPageContentStream contentStream = new PDPageContentStream(document, coverPage);
try {
int ypos = 760;
int xpos = 30;
int xwidth = 550;
int ygap = 20;
PDFont fontHelvetica = PDType1Font.HELVETICA;
PDFont fontHelveticaBold = PDType1Font.HELVETICA_BOLD;
PDFont fontHelveticaOblique = PDType1Font.HELVETICA_OBLIQUE;
contentStream.setNonStrokingColor(Color.BLACK);
String[][] content = { header1 };
drawTable(coverPage, contentStream, ypos, xpos, content, fontHelveticaBold, 11, false);
ypos -= (ygap);
String[][] content2 = { header2 };
drawTable(coverPage, contentStream, ypos, xpos, content2, fontHelveticaBold, 11, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
String[][] content3 = { { getOwningCommunity(item), getOwningCollection(item) } };
drawTable(coverPage, contentStream, ypos, xpos, content3, fontHelvetica, 9, false);
ypos -= ygap;
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap * 2);
for (String field : fields) {
field = field.trim();
PDFont font = fontHelvetica;
int fontSize = 11;
if (field.contains("title")) {
fontSize = 26;
ypos -= ygap;
} else if (field.contains("creator") || field.contains("contributor")) {
fontSize = 16;
}
if (field.equals("_line_")) {
contentStream.fillRect(xpos, ypos, xwidth, 1);
contentStream.closeAndStroke();
ypos -= (ygap);
} else if (StringUtils.isNotEmpty(item.getMetadata(field))) {
ypos = drawStringWordWrap(coverPage, contentStream, item.getMetadata(field), xpos, ypos, font, fontSize);
}
if (field.contains("title")) {
ypos -= ygap;
}
}
contentStream.beginText();
contentStream.setFont(fontHelveticaOblique, 11);
contentStream.moveTextPositionByAmount(xpos, ypos);
contentStream.drawString(footer);
contentStream.endText();
} finally {
contentStream.close();
}
}Example 23
| Project: webtest-master File: PdfBoxPDFPage.java View source code |
public List getFonts() {
final List<PDFBoxPDFFont> fonts = new ArrayList<PDFBoxPDFFont>();
final List pages = getPDFDocument().getDocumentCatalog().getAllPages();
for (final ListIterator iter = pages.listIterator(); iter.hasNext(); ) {
final PDPage page = (PDPage) iter.next();
try {
for (final Iterator fontIterator = page.findResources().getFonts().values().iterator(); fontIterator.hasNext(); ) {
final PDFont font = (PDFont) fontIterator.next();
// nextIndex() because page number start with 1 not 0
fonts.add(new PDFBoxPDFFont(font, iter.nextIndex()));
}
} catch (final IOException e) {
throw new RuntimeException("Failed retrieving the fonts on page " + iter.nextIndex(), e);
}
}
return fonts;
}Example 24
| Project: pdfxtk-master File: PDFObjectExtractor.java View source code |
/**
* You should override this method if you want to perform an action when a
* string is being shown.
*
* @param string The string to display.
*
* @throws IOException If there is an error showing the string
*/
public void showString(byte[] string, int argIndex) throws IOException {
OpTuple sourceOp = new OpTuple(opIndex, argIndex);
//super.showString(string);
ArrayList charactersToAdd = new ArrayList();
float[] individualWidths = new float[2048];
float spaceWidth = 0;
float spacing = 0;
StringBuffer stringResult = new StringBuffer(string.length);
float characterHorizontalDisplacement = 0;
float characterVerticalDisplacement = 0;
float spaceDisplacement = 0;
float fontSize = getGraphicsState().getTextState().getFontSize();
float horizontalScaling = getGraphicsState().getTextState().getHorizontalScalingPercent() / 100f;
//not sure if this is right but what else to do???
float verticalScaling = horizontalScaling;
float rise = getGraphicsState().getTextState().getRise();
final float wordSpacing = getGraphicsState().getTextState().getWordSpacing();
final float characterSpacing = getGraphicsState().getTextState().getCharacterSpacing();
float wordSpacingDisplacement = 0;
//We won't know the actual number of characters until
//we process the byte data(could be two bytes each) but
//it won't ever be more than string.length*2(there are some cases
//were a single byte will result in two output characters "fi"
PDFont font = getGraphicsState().getTextState().getFont();
//This will typically be 1000 but in the case of a type3 font
//this might be a different number
float glyphSpaceToTextSpaceFactor = 1f / font.getFontMatrix().getValue(0, 0);
float averageWidth = font.getAverageFontWidth();
Matrix initialMatrix = new Matrix();
initialMatrix.setValue(0, 0, 1);
initialMatrix.setValue(0, 1, 0);
initialMatrix.setValue(0, 2, 0);
initialMatrix.setValue(1, 0, 0);
initialMatrix.setValue(1, 1, 1);
initialMatrix.setValue(1, 2, 0);
initialMatrix.setValue(2, 0, 0);
initialMatrix.setValue(2, 1, rise);
initialMatrix.setValue(2, 2, 1);
//this
int codeLength = 1;
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
//lets see what the space displacement should be
spaceDisplacement = (font.getFontWidth(SPACE_BYTES, 0, 1) / glyphSpaceToTextSpaceFactor);
if (spaceDisplacement == 0) {
spaceDisplacement = (averageWidth / glyphSpaceToTextSpaceFactor);
//The average space width appears to be higher than necessary
//so lets make it a little bit smaller.
spaceDisplacement *= .80f;
}
int pageRotation = page.findRotation();
Matrix trm = initialMatrix.multiply(getTextMatrix()).multiply(ctm);
float x = trm.getValue(2, 0);
float y = trm.getValue(2, 1);
if (pageRotation == 0) {
trm.setValue(2, 1, -y + page.findMediaBox().getHeight());
} else if (pageRotation == 90 || pageRotation == -270) {
trm.setValue(2, 0, y);
//2013-03-12 fixed shifted coordinates in e.g. eu-014.pdf (table datset)
trm.setValue(2, 1, x);
// TODO: update GUI code to correct positioning of raster graphic
// trm.setValue( 2,1, x + page.findMediaBox().getHeight() - page.findMediaBox().getWidth() );
} else if (pageRotation == 270 || pageRotation == -90) {
trm.setValue(2, 0, -y + page.findMediaBox().getHeight());
trm.setValue(2, 1, x);
}
float xScale = trm.getXScale();
float yScale = trm.getYScale();
float xPos = trm.getXPosition();
float yPos = trm.getYPosition();
spaceWidth = spaceDisplacement * xScale * fontSize;
wordSpacingDisplacement = wordSpacing * xScale * fontSize;
float totalStringWidth = 0;
// addition 15.04.09
// to go back to older version, simply make x and yTrans 0
// this handles (more or less) edocsacs.pdf
float xPosBefore2 = getTextMatrix().getXPosition();
float yPosBefore2 = getTextMatrix().getYPosition();
float xTrans = 0, yTrans = 0;
if (pageRotation == 0) {
xTrans = xPos - xPosBefore2;
//System.out.println("xPos: " + xPos + " tmxp: " + getTextMatrix().getXPosition() + " xTrans: " + xTrans);
yTrans = yPos - yPosBefore2;
//System.out.println("yPos: " + yPos + " tmyp: " + getTextMatrix().getYPosition() + " yTrans: " + yTrans);
} else if (pageRotation == 90 || pageRotation == -270) {
xTrans = xPos - yPosBefore2;
///// System.out.println("xPos: " + xPos + " tmyp: " + getTextMatrix().getYPosition() + " xTrans: " + xTrans);
yTrans = yPos - xPosBefore2;
///// System.out.println("yPos: " + yPos + " tmxp: " + getTextMatrix().getXPosition() + " yTrans: " + yTrans);
} else if (pageRotation == 270 || pageRotation == -90) {
yTrans = xPos - yPosBefore2;
///// System.out.println("xPos: " + xPos + " tmyp: " + getTextMatrix().getYPosition() + " xTrans: " + xTrans);
xTrans = yPos - xPosBefore2;
///// System.out.println("yPos: " + yPos + " tmxp: " + getTextMatrix().getXPosition() + " yTrans: " + yTrans);
}
for (int i = 0; i < string.length; i += codeLength) {
codeLength = 1;
String c = font.encode(string, i, codeLength);
if (c == null && i + 1 < string.length) {
//maybe a multibyte encoding
codeLength++;
c = font.encode(string, i, codeLength);
}
//todo, handle horizontal displacement
// System.out.println("font: " + font + " font width: " + font.getFontWidth( string, i, codeLength ));
characterHorizontalDisplacement = (font.getFontWidth(string, i, codeLength) / glyphSpaceToTextSpaceFactor);
characterVerticalDisplacement = Math.max(characterVerticalDisplacement, font.getFontHeight(string, i, codeLength) / glyphSpaceToTextSpaceFactor);
//
if ((string[i] == 0x20) && c != null && c.equals(" ")) {
spacing = wordSpacing + characterSpacing;
} else {
spacing = characterSpacing;
}
// We want to update the textMatrix using the width, in text space units.
//
//The adjustment will always be zero. The adjustment as shown in the
//TJ operator will be handled separately.
float adjustment = 0;
//todo, need to compute the vertical displacement
float ty = 0;
float tx = ((characterHorizontalDisplacement - adjustment / glyphSpaceToTextSpaceFactor) * fontSize + spacing) * horizontalScaling;
// tx2, td2 added by TH sometime
float tx2 = (characterHorizontalDisplacement - adjustment / glyphSpaceToTextSpaceFactor) * fontSize * horizontalScaling;
// System.out.println("String: " + string + " tx: " + tx + " tx2: " + tx2);
// System.out.println("characterHorizontalDisplacement: " + characterHorizontalDisplacement);
// System.out.println("horizontalScaling: " + horizontalScaling);
// System.out.println("adjustment: " + adjustment);
tx2 = (characterHorizontalDisplacement) * fontSize * horizontalScaling;
Matrix td = new Matrix();
td.setValue(2, 0, tx);
td.setValue(2, 1, ty);
Matrix td2 = new Matrix();
td2.setValue(2, 0, tx2);
td2.setValue(2, 1, ty);
float xPosBefore = getTextMatrix().getXPosition();
float yPosBefore = getTextMatrix().getYPosition();
Matrix textMatrix2 = (Matrix) getTextMatrix().clone();
setTextMatrix(td.multiply(getTextMatrix()));
textMatrix2 = td2.multiply(textMatrix2);
/*
// addition 15.04.09
* moved above as it needs to be the same value for the string...
float xTrans = xPos - xPosBefore;
System.out.println("xTrans: " + xTrans);
float yTrans = yPos - yPosBefore;
System.out.println("yTrans: " + yTrans);
// end addition
*/
float width = 0, width2 = 0;
if (pageRotation == 0) {
width = (getTextMatrix().getXPosition() - xPosBefore);
width2 = (textMatrix2.getXPosition() - xPosBefore);
} else if (pageRotation == 90 || pageRotation == -270) {
width = (getTextMatrix().getYPosition() - yPosBefore);
width2 = (textMatrix2.getYPosition() - yPosBefore);
} else if (pageRotation == 270 || pageRotation == -90) {
width = (yPosBefore - getTextMatrix().getYPosition());
width2 = (yPosBefore - textMatrix2.getYPosition());
//width = (textMatrix.getYPosition() - yPosBefore);
//width2 = (textMatrix2.getYPosition() - yPosBefore);
}
//glyphname that has no mapping like "visiblespace"
if (c != null) {
float widthOfEachCharacterForCode = width / c.length();
for (int j = 0; j < c.length(); j++) {
if (stringResult.length() + j < individualWidths.length) {
if (c.equals("-")) {
//System.out.println( "stringResult.length()+j=" + (widthOfEachCharacterForCode));
}
individualWidths[stringResult.length() + j] = widthOfEachCharacterForCode;
}
}
}
totalStringWidth += width;
//System.out.println("new instruction: " + c +
// " width: " + width + " xPosBefore: " + xPosBefore + " yPosBefore: " + yPosBefore);
// TODO:
// with this code (incorrect results), try on matrox
// with indiv. characters as clusters (NG generation)
// to see whether the graph generation does actually terminate :)
/*
TextFragment thisChar = new TextFragment
(xPosBefore, xPosBefore + width, yPosBefore,
yPosBefore + + (fontSize * yScale), c, font, fontSize);
addCharacter(thisChar);
*/
CharSegment thisChar;
if (c == null)
c = "";
if (pageRotation == 0) {
//TextFragment
thisChar = new CharSegment(xPosBefore + xTrans, xPosBefore + width2 + xTrans, yPos, yPos + (fontSize * yScale), c, font, fontSize * yScale, sourceOp);
// addCharacter(thisChar, false);
//System.out.println("thisChar: " + thisChar);
charactersToAdd.add(thisChar);
} else // pageRotation == 90
{
/*
System.out.println("c: " + c + " yPosBefore: " + yPosBefore +
" (width:) " + width + " width2: " + width2 + " xPos: " + xPos +
" xPosBefore: " + xPosBefore + " yPos: " + yPos + " yPosBefore: "
+ yPosBefore +
" fontSize: " + fontSize + " xScale: " + xScale + " yScale: " +
yScale);
*/
// xScale? need to find a doc where they are different ;)
thisChar = new CharSegment(yPosBefore + xTrans, yPosBefore + width2 + xTrans, yPos, yPos + (fontSize * xScale), c, font, fontSize * xScale, sourceOp);
//System.out.println("thisChar: " + thisChar);
if (pageRotation == 270 || pageRotation == 90)
//addCharacter(thisChar, true);
charactersToAdd.add(thisChar);
else
//addCharacter(thisChar, false);
charactersToAdd.add(thisChar);
}
// System.out.println("yPos1.5: " + yPos);
stringResult.append(c);
}
// System.out.println("yPos2: " + yPos);
float totalStringHeight = characterVerticalDisplacement * fontSize * yScale;
String resultingString = stringResult.toString();
// System.out.println("yPos2.5: " + yPos);
if (individualWidths.length != resultingString.length()) {
float[] tmp = new float[resultingString.length()];
System.arraycopy(individualWidths, 0, tmp, 0, Math.min(individualWidths.length, resultingString.length()));
individualWidths = tmp;
if (resultingString.equals("- ")) {
//System.out.println( "EQUALS " + individualWidths[0] );
}
}
// System.out.println("yPos3: " + yPos);
float charX1 = xPos;
float charX2 = xPos + totalStringWidth;
float charY1 = yPos;
//totalStringHeight;
float charY2 = yPos + (fontSize * yScale);
String c = stringResult.toString();
//TextFragment thisChar = new TextFragment(charX1, charX2, charY1, charY2,
// c, font, fontSize * yScale);
//addCharacter(thisChar);
// System.out.println("showCharacter with xPos: " + xPos + " and yPos " + yPos + " and string " + stringResult.toString());
// addCharacter already called above
// showCharacter does nothing; neither in super nor in this class
/* start commented out 1.1
showCharacter(
new TextPosition(
xPos,
yPos,
xScale,
yScale,
totalStringWidth,
individualWidths,
totalStringHeight,
spaceWidth,
stringResult.toString(),
font,
fontSize,
wordSpacingDisplacement ));
//System.out.println("relief");
end commented out 1.1 */
//no call addCharacter for the list of characters to be processed...
CompositeSegment thisStringFragment = new CompositeSegment();
thisStringFragment.setText(stringResult.toString());
//System.out.println("stringResult: " + stringResult);
thisStringFragment.getItems().addAll(charactersToAdd);
thisStringFragment.findBoundingBox();
//System.out.println("thisStringFragment: " + thisStringFragment);
//System.out.println("lastStringFragment: " + lastStringFragment);
//float tolerance = fontSize * 0.05f;
// changed on 7.04.09 to allow for google19.pdf and other pdfs where yscale is used
// to determine fontsize...
float tolerance = fontSize * yScale * 0.05f;
if (lastStringFragment != null && thisStringFragment.getText().equals(lastStringFragment.getText()) && Utils.within(thisStringFragment.getX1(), lastStringFragment.getX1(), tolerance) && Utils.within(thisStringFragment.getX2(), lastStringFragment.getX2(), tolerance) && Utils.within(thisStringFragment.getY1(), lastStringFragment.getY1(), tolerance) && Utils.within(thisStringFragment.getY2(), lastStringFragment.getY2(), tolerance)) //if (false)
{
//System.out.println("stringResult overprint...");
// it's an overprint; code to come here
} else {
// add the text fragment!
Iterator<CharSegment> ctaIter = charactersToAdd.iterator();
while (ctaIter.hasNext()) {
CharSegment thisChar = ctaIter.next();
if (pageRotation == 270 || pageRotation == -90)
//if (pageRotation == 270 || pageRotation == 90)
addCharacter(thisChar, true);
else
addCharacter(thisChar, false);
}
}
lastStringFragment = thisStringFragment;
}Example 25
| Project: camel-master File: PdfUtils.java View source code |
public static float getAverageFontHeight(PDFont font, float fontSize) throws IOException {
return font.getFontHeight("A".getBytes(), 0, 1) / PDF_PIXEL_SIZE * fontSize;
}Example 26
| Project: ARX-master File: ElementText.java View source code |
/**
* Returns a styled instance
* @param font
* @param style
* @return
*/
protected PDFont style(BaseFont font, TextStyle style) {
switch(style) {
case PLAIN:
return font.getPlainFont();
case BOLD:
return font.getBoldFont();
case ITALIC:
return font.getItalicFont();
default:
return font.getPlainFont();
}
}Example 27
| Project: qi4j-sdk-master File: PDFWriter.java View source code |
private void setFont(PDFont font, float fontSize) {
curFont = font;
curFontSize = fontSize;
try {
curContentStream.setFont(curFont, curFontSize);
} catch (IOException e) {
throw new PrintingException("Unable to set font: " + font.toString() + ", " + fontSize + "pt", e);
}
}Example 28
| Project: drc-master File: PDFTextStripper2.java View source code |
public PDFont getFont() {
return src.getFont();
}