proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/AddJavascript.java
|
AddJavascript
|
main
|
class AddJavascript
{
private AddJavascript()
{
//static class, should not be instantiated.
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + AddJavascript.class.getName() + " <input-pdf> <output-pdf>" );
}
}
|
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PDActionJavaScript javascript = new PDActionJavaScript(
"app.alert( {cMsg: 'PDFBox rocks!', nIcon: 3, nType: 0, cTitle: 'PDFBox Javascript example' } );");
document.getDocumentCatalog().setOpenAction( javascript );
if( document.isEncrypted() )
{
throw new IOException( "Encrypted documents are not supported for this example" );
}
document.save( args[1] );
}
}
| 182
| 182
| 364
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMessageToEachPage.java
|
AddMessageToEachPage
|
main
|
class AddMessageToEachPage
{
/**
* Constructor.
*/
public AddMessageToEachPage()
{
super();
}
/**
* create the second sample document from the PDF file format specification.
*
* @param file The file to write the PDF to.
* @param message The message to write in the file.
* @param outfile The resulting PDF.
*
* @throws IOException If there is an error writing the data.
*/
public void doIt( String file, String message, String outfile ) throws IOException
{
try (PDDocument doc = Loader.loadPDF(new File(file)))
{
PDFont font = new PDType1Font(FontName.HELVETICA_BOLD);
float fontSize = 36.0f;
for( PDPage page : doc.getPages() )
{
PDRectangle pageSize = page.getMediaBox();
float stringWidth = font.getStringWidth( message )*fontSize/1000f;
// calculate to center of the page
int rotation = page.getRotation();
boolean rotate = rotation == 90 || rotation == 270;
float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
float centerX = rotate ? pageHeight/2f : (pageWidth - stringWidth)/2f;
float centerY = rotate ? (pageWidth - stringWidth)/2f : pageHeight/2f;
// append the content to the existing stream
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true))
{
contentStream.beginText();
// set font and font size
contentStream.setFont( font, fontSize );
// set text color to red
contentStream.setNonStrokingColor(Color.red);
if (rotate)
{
// rotate the text according to the page rotation
contentStream.setTextMatrix(Matrix.getRotateInstance(Math.PI / 2, centerX, centerY));
}
else
{
contentStream.setTextMatrix(Matrix.getTranslateInstance(centerX, centerY));
}
contentStream.showText(message);
contentStream.endText();
}
}
doc.save( outfile );
}
}
/**
* This will create a hello world PDF document.
* <br>
* see usage() for commandline
*
* @param args Command line arguments.
*/
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
System.err.println( "usage: " + this.getClass().getName() + " <input-file> <Message> <output-file>" );
}
}
|
AddMessageToEachPage app = new AddMessageToEachPage();
if( args.length != 3 )
{
app.usage();
}
else
{
app.doIt( args[0], args[1], args[2] );
}
| 759
| 71
| 830
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMetadataFromDocInfo.java
|
AddMetadataFromDocInfo
|
usage
|
class AddMetadataFromDocInfo
{
private AddMetadataFromDocInfo()
{
//utility class
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
* @throws TransformerException
*/
public static void main( String[] args ) throws IOException, TransformerException
{
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if (document.isEncrypted())
{
System.err.println( "Error: Cannot add metadata to encrypted document." );
System.exit( 1 );
}
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDDocumentInformation info = document.getDocumentInformation();
XMPMetadata metadata = XMPMetadata.createXMPMetadata();
AdobePDFSchema pdfSchema = metadata.createAndAddAdobePDFSchema();
pdfSchema.setKeywords( info.getKeywords() );
pdfSchema.setProducer( info.getProducer() );
XMPBasicSchema basicSchema = metadata.createAndAddXMPBasicSchema();
basicSchema.setModifyDate( info.getModificationDate() );
basicSchema.setCreateDate( info.getCreationDate() );
basicSchema.setCreatorTool( info.getCreator() );
basicSchema.setMetadataDate( new GregorianCalendar() );
DublinCoreSchema dcSchema = metadata.createAndAddDublinCoreSchema();
dcSchema.setTitle( info.getTitle() );
dcSchema.addCreator( "PDFBox" );
dcSchema.setDescription( info.getSubject() );
PDMetadata metadataStream = new PDMetadata(document);
catalog.setMetadata( metadataStream );
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(metadata, baos, false);
metadataStream.importXMPMetadata( baos.toByteArray() );
document.save( args[1] );
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{<FILL_FUNCTION_BODY>}
}
|
System.err.println( "Usage: java " + AddMetadataFromDocInfo.class.getName() + " <input-pdf> <output-pdf>" );
| 609
| 40
| 649
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/BengaliPdfGenerationHelloWorld.java
|
BengaliPdfGenerationHelloWorld
|
main
|
class BengaliPdfGenerationHelloWorld
{
private static final int LINE_GAP = 5;
private static final String LOHIT_BENGALI_TTF = "/org/apache/pdfbox/resources/ttf/Lohit-Bengali.ttf";
private static final String TEXT_SOURCE_FILE = "/org/apache/pdfbox/resources/ttf/bengali-samples.txt";
private static final int FONT_SIZE = 20;
private static final int MARGIN = 20;
private BengaliPdfGenerationHelloWorld()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static List<List<String>> getReAlignedTextBasedOnPageHeight(List<String> originalLines,
PDFont font, float workablePageHeight)
{
final float newLineHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000
* FONT_SIZE + LINE_GAP;
List<List<String>> realignedTexts = new ArrayList<>();
float consumedHeight = 0;
List<String> linesInAPage = new ArrayList<>();
for (String line : originalLines)
{
if (newLineHeight + consumedHeight < workablePageHeight)
{
consumedHeight += newLineHeight;
}
else
{
consumedHeight = newLineHeight;
realignedTexts.add(linesInAPage);
linesInAPage = new ArrayList<>();
}
linesInAPage.add(line);
}
realignedTexts.add(linesInAPage);
return realignedTexts;
}
private static List<String> getReAlignedTextBasedOnPageWidth(List<String> originalLines,
PDFont font, float workablePageWidth) throws IOException
{
List<String> uniformlyWideTexts = new ArrayList<>();
float consumedWidth = 0;
StringBuilder sb = new StringBuilder();
for (String line : originalLines)
{
float newTokenWidth = 0;
StringTokenizer st = new StringTokenizer(line, " ", true);
while (st.hasMoreElements())
{
String token = st.nextToken();
newTokenWidth = font.getStringWidth(token) / 1000 * FONT_SIZE;
if (newTokenWidth + consumedWidth < workablePageWidth)
{
consumedWidth += newTokenWidth;
}
else
{
// add a new text chunk
uniformlyWideTexts.add(sb.toString());
consumedWidth = newTokenWidth;
sb = new StringBuilder();
}
sb.append(token);
}
// add a new text chunk
uniformlyWideTexts.add(sb.toString());
consumedWidth = newTokenWidth;
sb = new StringBuilder();
}
return uniformlyWideTexts;
}
private static PDRectangle getPageSize()
{
return PDRectangle.A4;
}
private static List<String> getBengaliTextFromFile() throws IOException
{
List<String> lines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(
BengaliPdfGenerationHelloWorld.class.getResourceAsStream(TEXT_SOURCE_FILE), StandardCharsets.UTF_8)))
{
while (true)
{
String line = br.readLine();
if (line == null)
{
break;
}
if (!line.startsWith("#"))
{
lines.add(line);
}
}
}
return lines;
}
}
|
if (args.length != 1)
{
System.err.println(
"usage: " + BengaliPdfGenerationHelloWorld.class.getName() + " <output-file> ");
System.exit(1);
}
String filename = args[0];
System.out.println("The generated pdf filename is: " + filename);
try (PDDocument doc = new PDDocument())
{
PDFont font = PDType0Font.load(doc,
BengaliPdfGenerationHelloWorld.class.getResourceAsStream(LOHIT_BENGALI_TTF),
true);
PDRectangle rectangle = getPageSize();
float workablePageWidth = rectangle.getWidth() - 2 * MARGIN;
float workablePageHeight = rectangle.getHeight() - 2 * MARGIN;
List<List<String>> pagedTexts = getReAlignedTextBasedOnPageHeight(
getReAlignedTextBasedOnPageWidth(getBengaliTextFromFile(), font,
workablePageWidth),
font, workablePageHeight);
for (List<String> linesForPage : pagedTexts)
{
PDPage page = new PDPage(getPageSize());
doc.addPage(page);
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
contents.beginText();
contents.setFont(font, FONT_SIZE);
contents.newLineAtOffset(rectangle.getLowerLeftX() + MARGIN,
rectangle.getUpperRightY() - MARGIN);
for (String line : linesForPage)
{
contents.showText(line);
contents.newLineAtOffset(0, -(FONT_SIZE + LINE_GAP));
}
contents.endText();
}
}
doc.save(filename);
}
| 951
| 481
| 1,432
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreateBlankPDF.java
|
CreateBlankPDF
|
main
|
class CreateBlankPDF
{
private CreateBlankPDF()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 1)
{
System.err.println("usage: " + CreateBlankPDF.class.getName() + " <outputfile.pdf>");
System.exit(1);
}
String filename = args[0];
try (PDDocument doc = new PDDocument())
{
// a valid PDF document requires at least one page
PDPage blankPage = new PDPage();
doc.addPage(blankPage);
doc.save(filename);
}
| 55
| 132
| 187
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreateBookmarks.java
|
CreateBookmarks
|
usage
|
class CreateBookmarks
{
private CreateBookmarks()
{
//utility class
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if (document.isEncrypted())
{
System.err.println( "Error: Cannot add bookmarks to encrypted document." );
System.exit( 1 );
}
PDDocumentOutline outline = new PDDocumentOutline();
document.getDocumentCatalog().setDocumentOutline( outline );
PDOutlineItem pagesOutline = new PDOutlineItem();
pagesOutline.setTitle( "All Pages" );
outline.addLast( pagesOutline );
int pageNum = 0;
for( PDPage page : document.getPages() )
{
pageNum++;
PDPageDestination dest = new PDPageFitWidthDestination();
// If you want to have several bookmarks pointing to different areas
// on the same page, have a look at the other classes derived from PDPageDestination.
dest.setPage( page );
PDOutlineItem bookmark = new PDOutlineItem();
bookmark.setDestination( dest );
bookmark.setTitle( "Page " + pageNum );
pagesOutline.addLast( bookmark );
}
pagesOutline.openNode();
outline.openNode();
// optional: show the outlines when opening the file
document.getDocumentCatalog().setPageMode(PageMode.USE_OUTLINES);
document.save( args[1] );
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{<FILL_FUNCTION_BODY>}
}
|
System.err.println( "Usage: java " + CreateBookmarks.class.getName() + " <input-pdf> <output-pdf>" );
| 539
| 38
| 577
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreateLandscapePDF.java
|
CreateLandscapePDF
|
doIt
|
class CreateLandscapePDF
{
/**
* Constructor.
*/
public CreateLandscapePDF()
{
super();
}
/**
* creates a sample document with a landscape orientation and some text surrounded by a box.
*
* @param message The message to write in the file.
* @param outfile The resulting PDF.
*
* @throws IOException If there is an error writing the data.
*/
public void doIt( String message, String outfile ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will create a PDF document with a landscape orientation and some text surrounded by a box.
*
* @param args Command line arguments.
*/
public static void main(String[] args) throws IOException
{
CreateLandscapePDF app = new CreateLandscapePDF();
if( args.length != 2 )
{
app.usage();
}
else
{
app.doIt( args[0], args[1] );
}
}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
System.err.println( "usage: " + this.getClass().getName() + " <Message> <output-file>" );
}
}
|
try (PDDocument doc = new PDDocument())
{
PDFont font = new PDType1Font(FontName.HELVETICA);
PDPage page = new PDPage(PDRectangle.A4);
page.setRotation(90);
doc.addPage(page);
PDRectangle pageSize = page.getMediaBox();
float pageWidth = pageSize.getWidth();
float fontSize = 12;
float stringWidth = font.getStringWidth( message )*fontSize/1000f;
float startX = 100;
float startY = 100;
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false))
{
// add the rotation using the current transformation matrix
// including a translation of pageWidth to use the lower left corner as 0,0 reference
contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0));
contentStream.setFont( font, fontSize );
contentStream.beginText();
contentStream.newLineAtOffset(startX, startY);
contentStream.showText(message);
contentStream.newLineAtOffset(0, 100);
contentStream.showText(message);
contentStream.newLineAtOffset(100, 100);
contentStream.showText(message);
contentStream.endText();
contentStream.moveTo(startX-2, startY-2);
contentStream.lineTo(startX-2, startY+200+fontSize);
contentStream.stroke();
contentStream.moveTo(startX-2, startY+200+fontSize);
contentStream.lineTo(startX+100+stringWidth+2, startY+200+fontSize);
contentStream.stroke();
contentStream.moveTo(startX+100+stringWidth+2, startY+200+fontSize);
contentStream.lineTo(startX+100+stringWidth+2, startY-2);
contentStream.stroke();
contentStream.moveTo(startX+100+stringWidth+2, startY-2);
contentStream.lineTo(startX-2, startY-2);
contentStream.stroke();
}
doc.save( outfile );
}
| 333
| 617
| 950
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreatePDFA.java
|
CreatePDFA
|
main
|
class CreatePDFA
{
private CreatePDFA()
{
}
public static void main(String[] args) throws IOException, TransformerException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 3)
{
System.err.println("usage: " + CreatePDFA.class.getName() +
" <output-file> <Message> <ttf-file>");
System.exit(1);
}
String file = args[0];
String message = args[1];
String fontfile = args[2];
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// load the font as this needs to be embedded
PDFont font = PDType0Font.load(doc, new File(fontfile));
// A PDF/A file needs to have the font embedded if the font is used for text rendering
// in rendering modes other than text rendering mode 3.
//
// This requirement includes the PDF standard fonts, so don't use their static PDFType1Font classes such as
// PDFType1Font.HELVETICA.
//
// As there are many different font licenses it is up to the developer to check if the license terms for the
// font loaded allows embedding in the PDF.
//
if (!font.isEmbedded())
{
throw new IllegalStateException("PDF/A compliance requires that all fonts used for"
+ " text rendering in rendering modes other than rendering mode 3 are embedded.");
}
// create a page with the message
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
contents.beginText();
contents.setFont(font, 12);
contents.newLineAtOffset(100, 700);
contents.showText(message);
contents.endText();
}
// add XMP metadata
XMPMetadata xmp = XMPMetadata.createXMPMetadata();
try
{
DublinCoreSchema dc = xmp.createAndAddDublinCoreSchema();
dc.setTitle(file);
PDFAIdentificationSchema id = xmp.createAndAddPDFAIdentificationSchema();
id.setPart(1);
id.setConformance("B");
XmpSerializer serializer = new XmpSerializer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(xmp, baos, true);
PDMetadata metadata = new PDMetadata(doc);
metadata.importXMPMetadata(baos.toByteArray());
doc.getDocumentCatalog().setMetadata(metadata);
}
catch(BadFieldValueException e)
{
// won't happen here, as the provided value is valid
throw new IllegalArgumentException(e);
}
// sRGB output intent
InputStream colorProfile = CreatePDFA.class.getResourceAsStream(
"/org/apache/pdfbox/resources/pdfa/sRGB.icc");
PDOutputIntent intent = new PDOutputIntent(doc, colorProfile);
intent.setInfo("sRGB IEC61966-2.1");
intent.setOutputCondition("sRGB IEC61966-2.1");
intent.setOutputConditionIdentifier("sRGB IEC61966-2.1");
intent.setRegistryName("http://www.color.org");
doc.getDocumentCatalog().addOutputIntent(intent);
doc.save(file, CompressParameters.NO_COMPRESSION);
}
| 64
| 951
| 1,015
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreatePageLabels.java
|
CreatePageLabels
|
main
|
class CreatePageLabels
{
/**
* Constructor.
*/
private CreatePageLabels()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
try (PDDocument doc = new PDDocument())
{
doc.addPage(new PDPage());
doc.addPage(new PDPage());
doc.addPage(new PDPage());
PDPageLabels pageLabels = new PDPageLabels(doc);
PDPageLabelRange pageLabelRange1 = new PDPageLabelRange();
pageLabelRange1.setPrefix("RO ");
pageLabelRange1.setStart(3);
pageLabelRange1.setStyle(PDPageLabelRange.STYLE_ROMAN_UPPER);
pageLabels.setLabelItem(0, pageLabelRange1);
PDPageLabelRange pageLabelRange2 = new PDPageLabelRange();
pageLabelRange2.setStart(1);
pageLabelRange2.setStyle(PDPageLabelRange.STYLE_DECIMAL);
pageLabels.setLabelItem(2, pageLabelRange2);
doc.getDocumentCatalog().setPageLabels(pageLabels);
doc.save("labels.pdf");
}
| 65
| 264
| 329
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreatePatternsPDF.java
|
CreatePatternsPDF
|
main
|
class CreatePatternsPDF
{
private CreatePatternsPDF()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
page.setResources(new PDResources());
// Colored pattern, i.e. the pattern content stream will set its own color(s)
try (PDPageContentStream pcs = new PDPageContentStream(doc, page))
{
// Colored pattern, i.e. the pattern content stream will set its own color(s)
PDColorSpace patternCS1 = new PDPattern(null, PDDeviceRGB.INSTANCE);
// Table 75 spec
PDTilingPattern tilingPattern1 = new PDTilingPattern();
tilingPattern1.setBBox(new PDRectangle(0, 0, 10, 10));
tilingPattern1.setPaintType(PDTilingPattern.PAINT_COLORED);
tilingPattern1.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING);
tilingPattern1.setXStep(10);
tilingPattern1.setYStep(10);
COSName patternName1 = page.getResources().add(tilingPattern1);
try (PDPatternContentStream cs1 = new PDPatternContentStream(tilingPattern1))
{
// Set color, draw diagonal line + 2 more diagonals so that corners look good
cs1.setStrokingColor(Color.red);
cs1.moveTo(0, 0);
cs1.lineTo(10, 10);
cs1.moveTo(-1, 9);
cs1.lineTo(1, 11);
cs1.moveTo(9, -1);
cs1.lineTo(11, 1);
cs1.stroke();
}
PDColor patternColor1 = new PDColor(patternName1, patternCS1);
pcs.addRect(50, 500, 200, 200);
pcs.setNonStrokingColor(patternColor1);
pcs.fill();
// Uncolored pattern - the color is passed later
PDTilingPattern tilingPattern2 = new PDTilingPattern();
tilingPattern2.setBBox(new PDRectangle(0, 0, 10, 10));
tilingPattern2.setPaintType(PDTilingPattern.PAINT_UNCOLORED);
tilingPattern2.setTilingType(PDTilingPattern.TILING_NO_DISTORTION);
tilingPattern2.setXStep(10);
tilingPattern2.setYStep(10);
COSName patternName2 = page.getResources().add(tilingPattern2);
try (PDPatternContentStream cs2 = new PDPatternContentStream(tilingPattern2))
{
// draw a cross
cs2.moveTo(0, 5);
cs2.lineTo(10, 5);
cs2.moveTo(5, 0);
cs2.lineTo(5, 10);
cs2.stroke();
}
// Uncolored pattern colorspace needs to know the colorspace
// for the color values that will be passed when painting the fill
PDColorSpace patternCS2 = new PDPattern(null, PDDeviceRGB.INSTANCE);
PDColor patternColor2green = new PDColor(
new float[]{0,1,0},
patternName2,
patternCS2);
pcs.addRect(300, 500, 100, 100);
pcs.setNonStrokingColor(patternColor2green);
pcs.fill();
// same pattern again but with different color + different pattern start position
PDColor patternColor2blue = new PDColor(
new float[]{0,0,1},
patternName2,
patternCS2);
pcs.addRect(455, 505, 100, 100);
pcs.setNonStrokingColor(patternColor2blue);
pcs.fill();
}
doc.save("patterns.pdf");
}
| 53
| 1,093
| 1,146
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/CreateSeparationColorBox.java
|
CreateSeparationColorBox
|
main
|
class CreateSeparationColorBox
{
private CreateSeparationColorBox()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
COSArray separationArray = new COSArray();
separationArray.add(COSName.SEPARATION); // type
separationArray.add(COSName.getPDFName("Gold")); // the name, e.g. metallic, fluorescent, glitter
separationArray.add(COSName.DEVICERGB); // alternate colorspace
// tint transform function, results between C0=white (1 1 1) and C1=yellow (1 1 0)
COSDictionary fdict = new COSDictionary();
fdict.setInt(COSName.FUNCTION_TYPE, 2);
COSArray range = new COSArray();
range.add(COSInteger.ZERO);
range.add(COSInteger.ONE);
range.add(COSInteger.ZERO);
range.add(COSInteger.ONE);
range.add(COSInteger.ZERO);
range.add(COSInteger.ONE);
fdict.setItem(COSName.RANGE, range);
COSArray domain = new COSArray();
domain.add(COSInteger.ZERO);
domain.add(COSInteger.ONE);
fdict.setItem(COSName.DOMAIN, domain);
COSArray c0 = new COSArray();
c0.add(COSInteger.ONE);
c0.add(COSInteger.ONE);
c0.add(COSInteger.ONE);
fdict.setItem(COSName.C0, c0);
COSArray c1 = new COSArray();
c1.add(COSInteger.ONE);
c1.add(COSInteger.ONE);
c1.add(COSInteger.ZERO);
fdict.setItem(COSName.C1, c1);
fdict.setInt(COSName.N, 1);
PDFunctionType2 func = new PDFunctionType2(fdict);
separationArray.add(func);
PDColorSpace spotColorSpace = new PDSeparation(separationArray);
try (PDPageContentStream cs = new PDPageContentStream(doc, page))
{
PDColor color = new PDColor(new float[]{0.5f}, spotColorSpace);
cs.setStrokingColor(color);
cs.setLineWidth(10);
cs.addRect(50, 50, 500, 700);
cs.stroke();
}
doc.save("gold.pdf");
}
| 55
| 690
| 745
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedFiles.java
|
EmbeddedFiles
|
doIt
|
class EmbeddedFiles
{
/**
* Constructor.
*/
private EmbeddedFiles()
{
}
/**
* create the second sample document from the PDF file format specification.
*
* @param file The file to write the PDF to.
*
* @throws IOException If there is an error writing the data.
*/
public void doIt( String file) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will create a hello world PDF document with an embedded file.
* <br>
* see usage() for commandline
*
* @param args Command line arguments.
*/
public static void main(String[] args) throws IOException
{
EmbeddedFiles app = new EmbeddedFiles();
if( args.length != 1 )
{
app.usage();
}
else
{
app.doIt( args[0] );
}
}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
System.err.println( "usage: " + this.getClass().getName() + " <output-file>" );
}
}
|
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage( page );
PDFont font = new PDType1Font(FontName.HELVETICA_BOLD);
try (PDPageContentStream contentStream = new PDPageContentStream(doc, page))
{
contentStream.beginText();
contentStream.setFont( font, 12 );
contentStream.newLineAtOffset(100, 700);
contentStream.showText("Go to Document->File Attachments to View Embedded Files");
contentStream.endText();
}
//embedded files are stored in a named tree
PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
//first create the file specification, which holds the embedded file
PDComplexFileSpecification fs = new PDComplexFileSpecification();
// use both methods for backwards, cross-platform and cross-language compatibility.
fs.setFile( "Test.txt" );
fs.setFileUnicode("Test.txt");
//create a dummy file stream, this would probably normally be a FileInputStream
byte[] data = "This is the contents of the embedded file".getBytes(StandardCharsets.ISO_8859_1);
ByteArrayInputStream fakeFile = new ByteArrayInputStream(data);
PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile );
//now lets some of the optional parameters
ef.setSubtype( "text/plain" );
ef.setSize( data.length );
ef.setCreationDate( new GregorianCalendar() );
// use both methods for backwards, cross-platform and cross-language compatibility.
fs.setEmbeddedFile( ef );
fs.setEmbeddedFileUnicode(ef);
fs.setFileDescription("Very interesting file");
// create a new tree node and add the embedded file
PDEmbeddedFilesNameTreeNode treeNode = new PDEmbeddedFilesNameTreeNode();
treeNode.setNames( Collections.singletonMap( "My first attachment", fs ) );
// add the new node as kid to the root node
List<PDEmbeddedFilesNameTreeNode> kids = new ArrayList<>();
kids.add(treeNode);
efTree.setKids(kids);
// add the tree to the document catalog
PDDocumentNameDictionary names = new PDDocumentNameDictionary( doc.getDocumentCatalog() );
names.setEmbeddedFiles( efTree );
doc.getDocumentCatalog().setNames( names );
// show attachments panel in some viewers
doc.getDocumentCatalog().setPageMode(PageMode.USE_ATTACHMENTS);
doc.save( file );
}
| 313
| 714
| 1,027
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedFonts.java
|
EmbeddedFonts
|
main
|
class EmbeddedFonts
{
private EmbeddedFonts()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
try (PDDocument document = new PDDocument())
{
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
String dir = "../pdfbox/src/main/resources/org/apache/pdfbox/resources/ttf/";
PDType0Font font = PDType0Font.load(document, new File(dir + "LiberationSans-Regular.ttf"));
try (PDPageContentStream stream = new PDPageContentStream(document, page))
{
stream.beginText();
stream.setFont(font, 12);
stream.setLeading(12 * 1.2f);
stream.newLineAtOffset(50, 600);
stream.showText("PDFBox's Unicode with Embedded TrueType Font");
stream.newLine();
stream.showText("Supports full Unicode text ☺");
stream.newLine();
stream.showText("English русский язык Tiếng Việt");
stream.newLine();
// ligature
stream.showText("Ligatures: \uFB01lm \uFB02ood");
stream.endText();
}
document.save("example.pdf");
}
| 57
| 349
| 406
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedMultipleFonts.java
|
EmbeddedMultipleFonts
|
showTextMultiple
|
class EmbeddedMultipleFonts
{
private EmbeddedMultipleFonts()
{
}
public static void main(String[] args) throws IOException
{
try (PDDocument document = new PDDocument();
TrueTypeCollection ttc2 = new TrueTypeCollection(new File("c:/windows/fonts/batang.ttc"));
TrueTypeCollection ttc3 = new TrueTypeCollection(new File("c:/windows/fonts/mingliu.ttc")))
{
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDFont font1 = new PDType1Font(FontName.HELVETICA); // always have a simple font as first one
PDType0Font font2 = PDType0Font.load(document, ttc2.getFontByName("Batang"), true); // Korean
PDType0Font font3 = PDType0Font.load(document, ttc3.getFontByName("MingLiU"), true); // Chinese
PDType0Font font4 = PDType0Font.load(document, new File("c:/windows/fonts/mangal.ttf")); // Indian
PDType0Font font5 = PDType0Font.load(document, new File("c:/windows/fonts/ArialUni.ttf")); // Fallback
try (PDPageContentStream cs = new PDPageContentStream(document, page))
{
cs.beginText();
List<PDFont> fonts = new ArrayList<>();
fonts.add(font1);
fonts.add(font2);
fonts.add(font3);
fonts.add(font4);
fonts.add(font5);
cs.newLineAtOffset(20, 700);
showTextMultiple(cs, "abc 한국 中国 भारत 日本 abc", fonts, 20);
cs.endText();
}
document.save("example.pdf");
}
}
static void showTextMultiple(PDPageContentStream cs, String text, List<PDFont> fonts, float size)
throws IOException
{<FILL_FUNCTION_BODY>}
static boolean isWinAnsiEncoding(int unicode)
{
String name = GlyphList.getAdobeGlyphList().codePointToName(unicode);
if (".notdef".equals(name))
{
return false;
}
return WinAnsiEncoding.INSTANCE.contains(name);
}
}
|
try
{
// first try all at once
fonts.get(0).encode(text);
cs.setFont(fonts.get(0), size);
cs.showText(text);
return;
}
catch (IllegalArgumentException ex)
{
// do nothing
}
// now try separately
int i = 0;
while (i < text.length())
{
boolean found = false;
for (PDFont font : fonts)
{
try
{
String s = text.substring(i, i + 1);
font.encode(s);
// it works! Try more with this font
int j = i + 1;
for (; j < text.length(); ++j)
{
String s2 = text.substring(j, j + 1);
if (isWinAnsiEncoding(s2.codePointAt(0)) && font != fonts.get(0))
{
// Without this segment, the example would have a flaw:
// This code tries to keep the current font, so
// the second "abc" would appear in a different font
// than the first one, which would be weird.
// This segment assumes that the first font has WinAnsiEncoding.
// (all static PDType1Font Times / Helvetica / Courier fonts)
break;
}
try
{
font.encode(s2);
}
catch (IllegalArgumentException ex)
{
// it's over
break;
}
}
s = text.substring(i, j);
cs.setFont(font, size);
cs.showText(s);
i = j;
found = true;
break;
}
catch (IllegalArgumentException ex)
{
// didn't work, will try next font
}
}
if (!found)
{
throw new IllegalArgumentException("Could not show '" + text.charAt(i)
+ "' with the fonts provided");
}
}
| 650
| 516
| 1,166
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedVerticalFonts.java
|
EmbeddedVerticalFonts
|
main
|
class EmbeddedVerticalFonts
{
private EmbeddedVerticalFonts()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
// The actual font file
// Download: https://moji.or.jp/wp-content/ipafont/IPAfont/ipag00303.zip
// (free license: https://www.gnu.org/licenses/license-list.html#IPAFONT)
File ipafont = new File("ipag.ttf");
// You can also use a Windows 7 TrueType font collection, e.g. MingLiU:
// TrueTypeFont ttf = new TrueTypeCollection(new File("C:/windows/fonts/mingliu.ttc")).getFontByName("MingLiU")
// PDType0Font.loadVertical(document, ttf, true)
// Load as horizontal
PDType0Font hfont = PDType0Font.load(document, ipafont);
// Load as vertical
PDType0Font vfont = PDType0Font.loadVertical(document, ipafont);
// Load as vertical, but disable vertical glyph substitution
// (You will usually not want this because it doesn't look good!)
TrueTypeFont ttf = new TTFParser().parse(new RandomAccessReadBufferedFile(ipafont));
PDType0Font vfont2 = PDType0Font.loadVertical(document, ttf, true);
ttf.disableGsubFeature("vrt2");
ttf.disableGsubFeature("vert");
try (PDPageContentStream contentStream = new PDPageContentStream(document, page))
{
contentStream.beginText();
contentStream.setFont(hfont, 20);
contentStream.setLeading(25);
contentStream.newLineAtOffset(20, 300);
contentStream.showText("Key:");
contentStream.newLine();
contentStream.showText("① Horizontal");
contentStream.newLine();
contentStream.showText("② Vertical with substitution");
contentStream.newLine();
contentStream.showText("③ Vertical without substitution");
contentStream.endText();
contentStream.beginText();
contentStream.setFont(hfont, 20);
contentStream.newLineAtOffset(20, 650);
contentStream.showText("①「あーだこーだ」");
contentStream.endText();
contentStream.beginText();
contentStream.setFont(vfont, 20);
contentStream.newLineAtOffset(50, 600);
contentStream.showText("②「あーだこーだ」");
contentStream.endText();
contentStream.beginText();
contentStream.setFont(vfont2, 20);
contentStream.newLineAtOffset(100, 600);
contentStream.showText("③「あーだこーだ」");
contentStream.endText();
}
// result file should look like the one attached to JIRA issue PDFBOX-4106
document.save("vertical.pdf");
| 59
| 822
| 881
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractEmbeddedFiles.java
|
ExtractEmbeddedFiles
|
extractFilesFromEFTree
|
class ExtractEmbeddedFiles
{
private ExtractEmbeddedFiles()
{
}
/**
* This is the main method.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{
if( args.length != 1 )
{
usage();
System.exit(1);
}
File pdfFile = new File(args[0]);
String filePath = pdfFile.getParent() + FileSystems.getDefault().getSeparator();
try (PDDocument document = Loader.loadPDF(pdfFile))
{
PDDocumentNameDictionary namesDictionary =
new PDDocumentNameDictionary(document.getDocumentCatalog());
PDEmbeddedFilesNameTreeNode efTree = namesDictionary.getEmbeddedFiles();
if (efTree != null)
{
extractFilesFromEFTree(efTree, filePath);
}
// extract files from page annotations
for (PDPage page : document.getPages())
{
extractFilesFromPage(page, filePath);
}
}
}
private static void extractFilesFromPage(PDPage page, String filePath) throws IOException
{
for (PDAnnotation annotation : page.getAnnotations())
{
if (annotation instanceof PDAnnotationFileAttachment)
{
PDAnnotationFileAttachment annotationFileAttachment = (PDAnnotationFileAttachment) annotation;
PDFileSpecification fileSpec = annotationFileAttachment.getFile();
if (fileSpec instanceof PDComplexFileSpecification)
{
PDComplexFileSpecification complexFileSpec = (PDComplexFileSpecification) fileSpec;
PDEmbeddedFile embeddedFile = getEmbeddedFile(complexFileSpec);
if (embeddedFile != null)
{
extractFile(filePath, complexFileSpec.getFilename(), embeddedFile);
}
}
}
}
}
private static void extractFilesFromEFTree(PDNameTreeNode<PDComplexFileSpecification> efTree, String filePath) throws IOException
{<FILL_FUNCTION_BODY>}
private static void extractFiles(Map<String, PDComplexFileSpecification> names, String filePath)
throws IOException
{
for (Entry<String, PDComplexFileSpecification> entry : names.entrySet())
{
PDComplexFileSpecification fileSpec = entry.getValue();
PDEmbeddedFile embeddedFile = getEmbeddedFile(fileSpec);
if (embeddedFile != null)
{
extractFile(filePath, fileSpec.getFilename(), embeddedFile);
}
}
}
private static void extractFile(String filePath, String filename, PDEmbeddedFile embeddedFile)
throws IOException
{
String embeddedFilename = filePath + filename;
File file = new File(embeddedFilename);
File parentDir = file.getParentFile();
if (!parentDir.exists())
{
// sometimes paths contain a directory
System.out.println("Creating " + parentDir);
parentDir.mkdirs();
}
System.out.println("Writing " + embeddedFilename);
try (FileOutputStream fos = new FileOutputStream(file))
{
fos.write(embeddedFile.toByteArray());
}
}
private static PDEmbeddedFile getEmbeddedFile(PDComplexFileSpecification fileSpec )
{
// search for the first available alternative of the embedded file
PDEmbeddedFile embeddedFile = null;
if (fileSpec != null)
{
embeddedFile = fileSpec.getEmbeddedFileUnicode();
if (embeddedFile == null)
{
embeddedFile = fileSpec.getEmbeddedFileDos();
}
if (embeddedFile == null)
{
embeddedFile = fileSpec.getEmbeddedFileMac();
}
if (embeddedFile == null)
{
embeddedFile = fileSpec.getEmbeddedFileUnix();
}
if (embeddedFile == null)
{
embeddedFile = fileSpec.getEmbeddedFile();
}
}
return embeddedFile;
}
/**
* This will print the usage for this program.
*/
private static void usage()
{
System.err.println( "Usage: java " + ExtractEmbeddedFiles.class.getName() + " <input-pdf>" );
}
}
|
Map<String, PDComplexFileSpecification> names = efTree.getNames();
if (names != null)
{
extractFiles(names, filePath);
}
else
{
List<PDNameTreeNode<PDComplexFileSpecification>> kids = efTree.getKids();
if (kids == null)
{
return;
}
for (PDNameTreeNode<PDComplexFileSpecification> node : kids)
{
extractFilesFromEFTree(node, filePath);
}
}
| 1,306
| 161
| 1,467
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractMetadata.java
|
ExtractMetadata
|
format
|
class ExtractMetadata
{
private ExtractMetadata()
{
// utility class
}
/**
* This is the main method.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
* @throws XmpParsingException
* @throws BadFieldValueException
*/
public static void main(String[] args) throws IOException, XmpParsingException, BadFieldValueException
{
if (args.length != 1)
{
usage();
System.exit(1);
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PDDocumentCatalog catalog = document.getDocumentCatalog();
PDMetadata meta = catalog.getMetadata();
if (meta != null)
{
DomXmpParser xmpParser = new DomXmpParser();
try
{
XMPMetadata metadata = xmpParser.parse(meta.toByteArray());
showDublinCoreSchema(metadata);
showAdobePDFSchema(metadata);
showXMPBasicSchema(metadata);
}
catch (XmpParsingException e)
{
System.err.println("An error occurred when parsing the metadata: "
+ e.getMessage());
}
}
else
{
// The pdf doesn't contain any metadata, try to use the
// document information instead
PDDocumentInformation information = document.getDocumentInformation();
if (information != null)
{
showDocumentInformation(information);
}
}
}
}
}
private static void showXMPBasicSchema(XMPMetadata metadata)
{
XMPBasicSchema basic = metadata.getXMPBasicSchema();
if (basic != null)
{
display("Create Date:", basic.getCreateDate());
display("Modify Date:", basic.getModifyDate());
display("Creator Tool:", basic.getCreatorTool());
}
}
private static void showAdobePDFSchema(XMPMetadata metadata)
{
AdobePDFSchema pdf = metadata.getAdobePDFSchema();
if (pdf != null)
{
display("Keywords:", pdf.getKeywords());
display("PDF Version:", pdf.getPDFVersion());
display("PDF Producer:", pdf.getProducer());
}
}
private static void showDublinCoreSchema(XMPMetadata metadata) throws BadFieldValueException
{
DublinCoreSchema dc = metadata.getDublinCoreSchema();
if (dc != null)
{
display("Title:", dc.getTitle());
display("Description:", dc.getDescription());
listString("Creators: ", dc.getCreators());
listCalendar("Dates:", dc.getDates());
listString("Subjects:", dc.getSubjects());
}
}
private static void showDocumentInformation(PDDocumentInformation information)
{
display("Title:", information.getTitle());
display("Subject:", information.getSubject());
display("Author:", information.getAuthor());
display("Creator:", information.getCreator());
display("Producer:", information.getProducer());
}
private static void listString(String title, List<String> list)
{
if (list == null)
{
return;
}
System.out.println(title);
for (String string : list)
{
System.out.println(" " + string);
}
}
private static void listCalendar(String title, List<Calendar> list)
{
if (list == null)
{
return;
}
System.out.println(title);
for (Calendar calendar : list)
{
System.out.println(" " + format(calendar));
}
}
private static String format(Object o)
{<FILL_FUNCTION_BODY>}
private static void display(String title, Object value)
{
if (value != null)
{
System.out.println(title + " " + format(value));
}
}
/**
* This will print the usage for this program.
*/
private static void usage()
{
System.err.println("Usage: java " + ExtractMetadata.class.getName() + " <input-pdf>");
}
}
|
if (o instanceof Calendar)
{
Calendar cal = (Calendar) o;
return DateFormat.getDateInstance().format(cal.getTime());
}
else
{
return o.toString();
}
| 1,142
| 60
| 1,202
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ExtractTTFFonts.java
|
ExtractTTFFonts
|
writeFont
|
class ExtractTTFFonts
{
private int fontCounter = 1;
@SuppressWarnings({"squid:S2068"})
private static final String PASSWORD = "-password";
private static final String PREFIX = "-prefix";
private static final String ADDKEY = "-addkey";
private ExtractTTFFonts()
{
}
/**
* This is the entry point for the application.
*
* @param args The command-line arguments.
*
* @throws IOException If there is an error decrypting the document.
*/
public static void main(String[] args) throws IOException
{
ExtractTTFFonts extractor = new ExtractTTFFonts();
extractor.extractFonts(args);
}
private void extractFonts(String[] args) throws IOException
{
if (args.length < 1 || args.length > 4)
{
usage();
}
else
{
String pdfFile = null;
@SuppressWarnings({"squid:S2068"})
String password = "";
String prefix = null;
boolean addKey = false;
for (int i = 0; i < args.length; i++)
{
switch (args[i])
{
case PASSWORD:
i++;
if (i >= args.length)
{
usage();
}
password = args[i];
break;
case PREFIX:
i++;
if (i >= args.length)
{
usage();
}
prefix = args[i];
break;
case ADDKEY:
addKey = true;
break;
default:
if (pdfFile == null)
{
pdfFile = args[i];
}
break;
}
}
if (pdfFile == null)
{
usage();
}
else
{
if (prefix == null && pdfFile.length() > 4)
{
prefix = pdfFile.substring(0, pdfFile.length() - 4);
}
try (PDDocument document = Loader.loadPDF(new File(pdfFile), password))
{
for (PDPage page : document.getPages())
{
PDResources resources = page.getResources();
// extract all fonts which are part of the page resources
processResources(resources, prefix, addKey);
}
}
}
}
}
private void processResources(PDResources resources, String prefix, boolean addKey) throws IOException
{
if (resources == null)
{
return;
}
for (COSName key : resources.getFontNames())
{
PDFont font = resources.getFont(key);
// write the font
if (font instanceof PDTrueTypeFont)
{
String name;
if (addKey)
{
name = getUniqueFileName(prefix + "_" + key, "ttf");
}
else
{
name = getUniqueFileName(prefix, "ttf");
}
writeFont(font.getFontDescriptor(), name);
}
else if (font instanceof PDType0Font)
{
PDCIDFont descendantFont = ((PDType0Font) font).getDescendantFont();
if (descendantFont instanceof PDCIDFontType2)
{
String name;
if (addKey)
{
name = getUniqueFileName(prefix + "_" + key, "ttf");
}
else
{
name = getUniqueFileName(prefix, "ttf");
}
writeFont(descendantFont.getFontDescriptor(), name);
}
}
}
for (COSName name : resources.getXObjectNames())
{
PDXObject xobject = resources.getXObject(name);
if (xobject instanceof PDFormXObject)
{
PDFormXObject xObjectForm = (PDFormXObject) xobject;
PDResources formResources = xObjectForm.getResources();
processResources(formResources, prefix, addKey);
}
}
}
private void writeFont(PDFontDescriptor fd, String name) throws IOException
{<FILL_FUNCTION_BODY>}
private String getUniqueFileName(String prefix, String suffix)
{
String uniqueName = null;
File f = null;
while (f == null || f.exists())
{
uniqueName = prefix + "-" + fontCounter;
f = new File(uniqueName + "." + suffix);
fontCounter++;
}
return uniqueName;
}
/**
* This will print the usage requirements and exit.
*/
private static void usage()
{
System.err.println("Usage: java " + ExtractTTFFonts.class.getName() + " [OPTIONS] <PDF file>\n"
+ " -password <password> Password to decrypt document\n"
+ " -prefix <font-prefix> Font prefix(default to pdf name)\n"
+ " -addkey add the internal font key to the file name\n"
+ " <PDF file> The PDF document to use\n");
System.exit(1);
}
}
|
if (fd != null)
{
PDStream ff2Stream = fd.getFontFile2();
if (ff2Stream != null)
{
System.out.println("Writing font: " + name);
try (OutputStream os = new FileOutputStream(name + ".ttf");
InputStream is = ff2Stream.createInputStream())
{
is.transferTo(os);
}
}
}
| 1,355
| 114
| 1,469
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/GoToSecondBookmarkOnOpen.java
|
GoToSecondBookmarkOnOpen
|
main
|
class GoToSecondBookmarkOnOpen
{
private GoToSecondBookmarkOnOpen()
{
//utility class
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + GoToSecondBookmarkOnOpen.class.getName() +
"<input-pdf> <output-pdf>" );
}
}
|
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if( document.isEncrypted() )
{
System.err.println( "Error: Cannot add bookmark destination to encrypted documents." );
System.exit( 1 );
}
if( document.getNumberOfPages() < 2 )
{
throw new IOException( "Error: The PDF must have at least 2 pages.");
}
PDDocumentOutline bookmarks = document.getDocumentCatalog().getDocumentOutline();
if( bookmarks == null )
{
throw new IOException( "Error: The PDF does not contain any bookmarks" );
}
PDOutlineItem item = bookmarks.getFirstChild().getNextSibling();
PDDestination dest = item.getDestination();
PDActionGoTo action = new PDActionGoTo();
action.setDestination(dest);
document.getDocumentCatalog().setOpenAction(action);
document.save( args[1] );
}
}
| 187
| 294
| 481
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorld.java
|
HelloWorld
|
main
|
class HelloWorld
{
private HelloWorld()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if( args.length != 2 )
{
System.err.println("usage: " + HelloWorld.class.getName() + " <output-file> <Message>");
System.exit(1);
}
String filename = args[0];
String message = args[1];
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
PDFont font = new PDType1Font(FontName.HELVETICA_BOLD);
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
contents.beginText();
contents.setFont(font, 12);
contents.newLineAtOffset(100, 700);
contents.showText(message);
contents.endText();
}
doc.save(filename);
}
| 52
| 240
| 292
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorldTTF.java
|
HelloWorldTTF
|
main
|
class HelloWorldTTF
{
private HelloWorldTTF()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 3)
{
System.err.println("usage: " + HelloWorldTTF.class.getName() +
" <output-file> <Message> <ttf-file>");
System.exit(1);
}
String pdfPath = args[0];
String message = args[1];
String ttfPath = args[2];
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
PDFont font = PDType0Font.load(doc, new File(ttfPath));
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
contents.beginText();
contents.setFont(font, 12);
contents.newLineAtOffset(100, 700);
contents.showText(message);
contents.endText();
}
doc.save(pdfPath);
System.out.println(pdfPath + " created!");
}
| 55
| 274
| 329
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorldType1.java
|
HelloWorldType1
|
main
|
class HelloWorldType1
{
private HelloWorldType1()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 3)
{
System.err.println("usage: " + HelloWorldType1.class.getName() +
" <output-file> <Message> <pfb-file>");
System.exit(1);
}
String file = args[0];
String message = args[1];
String pfbPath = args[2];
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
PDFont font;
try (InputStream is = new FileInputStream(pfbPath))
{
font = new PDType1Font(doc, is);
}
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
contents.beginText();
contents.setFont(font, 12);
contents.newLineAtOffset(100, 700);
contents.showText(message);
contents.endText();
}
doc.save(file);
System.out.println(file + " created!");
}
| 57
| 289
| 346
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ImageToPDF.java
|
ImageToPDF
|
main
|
class ImageToPDF
{
private ImageToPDF()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 2)
{
System.err.println("usage: " + ImageToPDF.class.getName() + " <image> <output-file>");
System.exit(1);
}
String imagePath = args[0];
String pdfPath = args[1];
if (!pdfPath.endsWith(".pdf"))
{
System.err.println("Last argument must be the destination .pdf file");
System.exit(1);
}
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
// draw the image at full size at (x=20, y=20)
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
// draw the image at full size at (x=20, y=20)
contents.drawImage(pdImage, 20, 20);
// to draw the image at half size at (x=20, y=20) use
// contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 2, pdImage.getHeight() / 2);
}
doc.save(pdfPath);
}
| 52
| 404
| 456
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintBookmarks.java
|
PrintBookmarks
|
printBookmark
|
class PrintBookmarks
{
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{
if( args.length != 1 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PrintBookmarks meta = new PrintBookmarks();
PDDocumentOutline outline = document.getDocumentCatalog().getDocumentOutline();
if( outline != null )
{
meta.printBookmark(document, outline, "");
}
else
{
System.out.println( "This document does not contain any bookmarks" );
}
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + PrintBookmarks.class.getName() + " <input-pdf>" );
}
/**
* This will print the documents bookmarks to System.out.
*
* @param document The document.
* @param bookmark The bookmark to print out.
* @param indentation A pretty printing parameter
*
* @throws IOException If there is an error getting the page count.
*/
public void printBookmark(PDDocument document, PDOutlineNode bookmark, String indentation) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
PDOutlineItem current = bookmark.getFirstChild();
while( current != null )
{
// one could also use current.findDestinationPage(document) to get the page number,
// but this example does it the hard way to explain the different types
// Note that bookmarks can also do completely different things, e.g. link to a website,
// or to an external file. This example focuses on internal pages.
if (current.getDestination() instanceof PDPageDestination)
{
PDPageDestination pd = (PDPageDestination) current.getDestination();
System.out.println(indentation + "Destination page: " + (pd.retrievePageNumber() + 1));
}
else if (current.getDestination() instanceof PDNamedDestination)
{
PDPageDestination pd = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) current.getDestination());
if (pd != null)
{
System.out.println(indentation + "Destination page: " + (pd.retrievePageNumber() + 1));
}
}
else if (current.getDestination() != null)
{
System.out.println(indentation + "Destination class: " + current.getDestination().getClass().getSimpleName());
}
if (current.getAction() instanceof PDActionGoTo)
{
PDActionGoTo gta = (PDActionGoTo) current.getAction();
if (gta.getDestination() instanceof PDPageDestination)
{
PDPageDestination pd = (PDPageDestination) gta.getDestination();
System.out.println(indentation + "Destination page: " + (pd.retrievePageNumber() + 1));
}
else if (gta.getDestination() instanceof PDNamedDestination)
{
PDPageDestination pd = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) gta.getDestination());
if (pd != null)
{
System.out.println(indentation + "Destination page: " + (pd.retrievePageNumber() + 1));
}
}
else
{
System.out.println(indentation + "Destination class: " + gta.getDestination().getClass().getSimpleName());
}
}
else if (current.getAction() != null)
{
System.out.println(indentation + "Action class: " + current.getAction().getClass().getSimpleName());
}
System.out.println( indentation + current.getTitle() );
printBookmark( document, current, indentation + " " );
current = current.getNextSibling();
}
| 411
| 702
| 1,113
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintDocumentMetaData.java
|
PrintDocumentMetaData
|
printMetadata
|
class PrintDocumentMetaData
{
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{
if( args.length != 1 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PrintDocumentMetaData meta = new PrintDocumentMetaData();
meta.printMetadata( document );
}
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + PrintDocumentMetaData.class.getName() + " <input-pdf>" );
}
/**
* This will print the documents data to System.out.
*
* @param document The document to get the metadata from.
*
* @throws IOException If there is an error getting the page count.
*/
public void printMetadata( PDDocument document ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will format a date object.
*
* @param date The date to format.
*
* @return A string representation of the date.
*/
private String formatDate( Calendar date )
{
String retval = null;
if( date != null )
{
SimpleDateFormat formatter = new SimpleDateFormat();
retval = formatter.format( date.getTime() );
}
return retval;
}
}
|
PDDocumentInformation info = document.getDocumentInformation();
PDDocumentCatalog cat = document.getDocumentCatalog();
PDMetadata metadata = cat.getMetadata();
System.out.println( "Page Count=" + document.getNumberOfPages() );
System.out.println( "Title=" + info.getTitle() );
System.out.println( "Author=" + info.getAuthor() );
System.out.println( "Subject=" + info.getSubject() );
System.out.println( "Keywords=" + info.getKeywords() );
System.out.println( "Creator=" + info.getCreator() );
System.out.println( "Producer=" + info.getProducer() );
System.out.println( "Creation Date=" + formatDate( info.getCreationDate() ) );
System.out.println( "Modification Date=" + formatDate( info.getModificationDate() ) );
System.out.println( "Trapped=" + info.getTrapped() );
if( metadata != null )
{
String string = new String( metadata.toByteArray(), StandardCharsets.ISO_8859_1 );
System.out.println( "Metadata=" + string );
}
| 431
| 319
| 750
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintURLs.java
|
PrintURLs
|
main
|
class PrintURLs
{
/**
* Constructor.
*/
private PrintURLs()
{
//utility class
}
/**
* This will output all URLs and the texts in the annotation rectangle of a document.
* <br>
* see usage() for commandline
*
* @param args Command line arguments.
*
* @throws IOException If there is an error extracting the URLs.
*/
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static PDActionURI getActionURI(PDAnnotation annot)
{
// use reflection to catch all annotation types that have getAction()
// If you can't use reflection, then check for classes
// PDAnnotationLink and PDAnnotationWidget, and call getAction() and check for a
// PDActionURI result type
try
{
Method actionMethod = annot.getClass().getDeclaredMethod("getAction");
if (actionMethod.getReturnType().equals(PDAction.class))
{
PDAction action = (PDAction) actionMethod.invoke(annot);
if (action instanceof PDActionURI)
{
return (PDActionURI) action;
}
}
}
catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
{
}
return null;
}
/**
* This will print out a message telling how to use this example.
*/
private static void usage()
{
System.err.println( "usage: " + PrintURLs.class.getName() + " <input-file>" );
}
}
|
PDDocument doc = null;
try
{
if( args.length != 1 )
{
usage();
}
else
{
doc = Loader.loadPDF(new File(args[0]));
int pageNum = 0;
for( PDPage page : doc.getPages() )
{
pageNum++;
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
List<PDAnnotation> annotations = page.getAnnotations();
//first setup text extraction regions
for( int j=0; j<annotations.size(); j++ )
{
PDAnnotation annot = annotations.get(j);
if (getActionURI(annot) != null)
{
PDRectangle rect = annot.getRectangle();
//need to reposition link rectangle to match text space
float x = rect.getLowerLeftX();
float y = rect.getUpperRightY();
float width = rect.getWidth();
float height = rect.getHeight();
int rotation = page.getRotation();
if( rotation == 0 )
{
PDRectangle pageSize = page.getMediaBox();
// area stripper uses java coordinates, not PDF coordinates
y = pageSize.getHeight() - y;
}
else
{
// do nothing
// please send us a sample file
}
Rectangle2D.Float awtRect = new Rectangle2D.Float( x,y,width,height );
stripper.addRegion( "" + j, awtRect );
}
}
stripper.extractRegions( page );
for( int j=0; j<annotations.size(); j++ )
{
PDAnnotation annot = annotations.get(j);
PDActionURI uri = getActionURI(annot);
if (uri != null)
{
String urlText = stripper.getTextForRegion("" + j);
System.out.println("Page " + pageNum + ":'" + urlText.trim() + "'=" + uri.getURI());
}
}
}
}
}
finally
{
if( doc != null )
{
doc.close();
}
}
| 422
| 581
| 1,003
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RemoveFirstPage.java
|
RemoveFirstPage
|
main
|
class RemoveFirstPage
{
private RemoveFirstPage()
{
//utility class, should not be instantiated.
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + RemoveFirstPage.class.getName() + " <input-pdf> <output-pdf>" );
}
}
|
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if( document.isEncrypted() )
{
throw new IOException( "Encrypted documents are not supported for this example" );
}
if( document.getNumberOfPages() <= 1 )
{
throw new IOException( "Error: A PDF document must have at least one page, " +
"cannot remove the last page!");
}
document.removePage( 0 );
document.save( args[1] );
}
}
| 180
| 170
| 350
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ReplaceURLs.java
|
ReplaceURLs
|
main
|
class ReplaceURLs
{
/**
* Constructor.
*/
private ReplaceURLs()
{
//utility class
}
/**
* This will read in a document and replace all of the urls with
* http://pdfbox.apache.org.
* <br>
* see usage() for commandline
*
* @param args Command line arguments.
*
* @throws IOException If there is an error during the process.
*/
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print out a message telling how to use this example.
*/
private static void usage()
{
System.err.println( "usage: " + ReplaceURLs.class.getName() + " <input-file> <output-file>" );
}
}
|
PDDocument doc = null;
try
{
if( args.length != 2 )
{
usage();
}
else
{
doc = Loader.loadPDF(new File(args[0]));
int pageNum = 0;
for( PDPage page : doc.getPages() )
{
pageNum++;
List<PDAnnotation> annotations = page.getAnnotations();
for (PDAnnotation annotation : annotations)
{
PDAnnotation annot = annotation;
if( annot instanceof PDAnnotationLink )
{
PDAnnotationLink link = (PDAnnotationLink)annot;
PDAction action = link.getAction();
if( action instanceof PDActionURI )
{
PDActionURI uri = (PDActionURI)action;
String oldURI = uri.getURI();
String newURI = "http://pdfbox.apache.org";
System.out.println( "Page " + pageNum +": Replacing " + oldURI + " with " + newURI );
uri.setURI( newURI );
}
}
}
}
doc.save( args[1] );
}
}
finally
{
if( doc != null )
{
doc.close();
}
}
| 223
| 333
| 556
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStamp.java
|
RubberStamp
|
main
|
class RubberStamp
{
private RubberStamp()
{
//utility class, should not be instantiated.
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + RubberStamp.class.getName() + " <input-pdf> <output-pdf>" );
}
}
|
if( args.length != 2 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if( document.isEncrypted() )
{
throw new IOException( "Encrypted documents are not supported for this example" );
}
for (PDPage page : document.getPages())
{
List<PDAnnotation> annotations = page.getAnnotations();
PDAnnotationRubberStamp rs = new PDAnnotationRubberStamp();
rs.setName(PDAnnotationRubberStamp.NAME_TOP_SECRET);
rs.setRectangle(new PDRectangle(100, 100));
rs.setContents("A top secret note");
annotations.add(rs);
}
document.save( args[1] );
}
}
| 183
| 240
| 423
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStampWithImage.java
|
RubberStampWithImage
|
doIt
|
class RubberStampWithImage
{
private static final String SAVE_GRAPHICS_STATE = "q\n";
private static final String RESTORE_GRAPHICS_STATE = "Q\n";
private static final String CONCATENATE_MATRIX = "cm\n";
private static final String XOBJECT_DO = "Do\n";
private static final String SPACE = " ";
private static final NumberFormat FORMATDECIMAL = NumberFormat.getNumberInstance( Locale.US );
/**
* Add a rubber stamp with an jpg image to every page of the given document.
* @param args the command line arguments
* @throws IOException an exception is thrown if something went wrong
*/
public void doIt( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
private void drawXObject( PDImageXObject xobject, PDResources resources, OutputStream os,
float x, float y, float width, float height ) throws IOException
{
// This is similar to PDPageContentStream.drawXObject()
COSName xObjectId = resources.add(xobject);
appendRawCommands( os, SAVE_GRAPHICS_STATE );
appendRawCommands( os, FORMATDECIMAL.format( width ) );
appendRawCommands( os, SPACE );
appendRawCommands( os, FORMATDECIMAL.format( 0 ) );
appendRawCommands( os, SPACE );
appendRawCommands( os, FORMATDECIMAL.format( 0 ) );
appendRawCommands( os, SPACE );
appendRawCommands( os, FORMATDECIMAL.format( height ) );
appendRawCommands( os, SPACE );
appendRawCommands( os, FORMATDECIMAL.format( x ) );
appendRawCommands( os, SPACE );
appendRawCommands( os, FORMATDECIMAL.format( y ) );
appendRawCommands( os, SPACE );
appendRawCommands( os, CONCATENATE_MATRIX );
appendRawCommands( os, SPACE );
appendRawCommands( os, "/" );
appendRawCommands( os, xObjectId.getName() );
appendRawCommands( os, SPACE );
appendRawCommands( os, XOBJECT_DO );
appendRawCommands( os, SPACE );
appendRawCommands( os, RESTORE_GRAPHICS_STATE );
}
private void appendRawCommands(OutputStream os, String commands) throws IOException
{
os.write( commands.getBytes(StandardCharsets.ISO_8859_1));
}
/**
* This creates an instance of RubberStampWithImage.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{
RubberStampWithImage rubberStamp = new RubberStampWithImage();
rubberStamp.doIt(args);
}
/**
* This will print the usage for this example.
*/
private void usage()
{
System.err.println( "Usage: java "+getClass().getName()+" <input-pdf> <output-pdf> <image-filename>" );
}
}
|
if( args.length != 3 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if( document.isEncrypted() )
{
throw new IOException( "Encrypted documents are not supported for this example" );
}
for (int i = 0; i < document.getNumberOfPages(); i++)
{
PDPage page = document.getPage(i);
List<PDAnnotation> annotations = page.getAnnotations();
PDAnnotationRubberStamp rubberStamp = new PDAnnotationRubberStamp();
rubberStamp.setName(PDAnnotationRubberStamp.NAME_TOP_SECRET);
rubberStamp.setRectangle(new PDRectangle(200,100));
rubberStamp.setContents("A top secret note");
// create a PDXObjectImage with the given image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject ximage = PDImageXObject.createFromFile(args[2], document);
// define and set the target rectangle
float lowerLeftX = 250;
float lowerLeftY = 550;
float formWidth = 150;
float formHeight = 25;
float imgWidth = 50;
float imgHeight = 25;
PDRectangle rect = new PDRectangle();
rect.setLowerLeftX(lowerLeftX);
rect.setLowerLeftY(lowerLeftY);
rect.setUpperRightX(lowerLeftX + formWidth);
rect.setUpperRightY(lowerLeftY + formHeight);
// Create a PDFormXObject
PDFormXObject form = new PDFormXObject(document);
form.setResources(new PDResources());
form.setBBox(rect);
form.setFormType(1);
// adjust the image to the target rectangle and add it to the stream
try (OutputStream os = form.getStream().createOutputStream())
{
drawXObject(ximage, form.getResources(), os, lowerLeftX, lowerLeftY, imgWidth, imgHeight);
}
PDAppearanceStream myDic = new PDAppearanceStream(form.getCOSObject());
PDAppearanceDictionary appearance = new PDAppearanceDictionary(new COSDictionary());
appearance.setNormalAppearance(myDic);
rubberStamp.setAppearance(appearance);
rubberStamp.setRectangle(rect);
// add the new RubberStamp to the document
annotations.add(rubberStamp);
}
document.save( args[1] );
}
}
| 859
| 722
| 1,581
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ShowColorBoxes.java
|
ShowColorBoxes
|
main
|
class ShowColorBoxes
{
private ShowColorBoxes()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 1)
{
System.err.println("usage: " +ShowColorBoxes.class.getName() + " <output-file>");
System.exit(1);
}
String filename = args[0];
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// fill the entire background with cyan
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
// fill the entire background with cyan
contents.setNonStrokingColor(Color.CYAN);
contents.addRect(0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
contents.fill();
// draw a red box in the lower left hand corner
contents.setNonStrokingColor(Color.RED);
contents.addRect(10, 10, 100, 100);
contents.fill();
// draw a blue box with rect x=200, y=500, w=200, h=100
// 105° rotation is around the bottom left corner
contents.saveGraphicsState();
contents.setNonStrokingColor(Color.BLUE);
contents.transform(Matrix.getRotateInstance(Math.toRadians(105), 200, 500));
contents.addRect(0, 0, 200, 100);
contents.fill();
contents.restoreGraphicsState();
}
doc.save(filename);
}
| 55
| 422
| 477
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ShowTextWithPositioning.java
|
ShowTextWithPositioning
|
doIt
|
class ShowTextWithPositioning
{
private static final float FONT_SIZE = 20.0f;
private ShowTextWithPositioning()
{
}
public static void main(String[] args) throws IOException
{
doIt("Hello World, this is a test!", "justify-example.pdf");
}
public static void doIt(String message, String outfile) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// the document
try (PDDocument doc = new PDDocument();
InputStream is = PDDocument.class.getResourceAsStream("/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"))
{
// Page 1
PDFont font = PDType0Font.load(doc, is, true);
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);
// Get the non-justified string width in text space units.
float stringWidth = font.getStringWidth(message) * FONT_SIZE;
// Get the string height in text space units.
float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * FONT_SIZE;
// Get the width we have to justify in.
PDRectangle pageSize = page.getMediaBox();
try (PDPageContentStream contentStream = new PDPageContentStream(doc,
page, AppendMode.OVERWRITE, false))
{
contentStream.beginText();
contentStream.setFont(font, FONT_SIZE);
// Start at top of page.
contentStream.setTextMatrix(
Matrix.getTranslateInstance(0, pageSize.getHeight() - stringHeight / 1000f));
// First show non-justified.
contentStream.showText(message);
// Move to next line.
contentStream.setTextMatrix(
Matrix.getTranslateInstance(0, pageSize.getHeight() - stringHeight / 1000f * 2));
// Now show word justified.
// The space we have to make up, in text space units.
float justifyWidth = pageSize.getWidth() * 1000f - stringWidth;
List<Object> text = new ArrayList<>();
String[] parts = StringUtil.splitOnSpace(message);
float spaceWidth = (justifyWidth / (parts.length - 1)) / FONT_SIZE;
for (int i = 0; i < parts.length; i++)
{
if (i != 0)
{
text.add(" ");
// Positive values move to the left, negative to the right.
text.add(-spaceWidth);
}
text.add(parts[i]);
}
contentStream.showTextWithPositioning(text.toArray());
contentStream.setTextMatrix(Matrix.getTranslateInstance(0, pageSize.getHeight() - stringHeight / 1000f * 3));
// Now show letter justified.
text = new ArrayList<>();
justifyWidth = pageSize.getWidth() * 1000f - stringWidth;
float extraLetterWidth = (justifyWidth / (message.codePointCount(0, message.length()) - 1)) / FONT_SIZE;
for (int i = 0; i < message.length(); i += Character.charCount(message.codePointAt(i)))
{
if (i != 0)
{
text.add(-extraLetterWidth);
}
text.add(String.valueOf(Character.toChars(message.codePointAt(i))));
}
contentStream.showTextWithPositioning(text.toArray());
// PDF specification about word spacing:
// "Word spacing shall be applied to every occurrence of the single-byte character
// code 32 in a string when using a simple font or a composite font that defines
// code 32 as a single-byte code. It shall not apply to occurrences of the byte
// value 32 in multiple-byte codes.
// TrueType font with no word spacing
contentStream.setTextMatrix(
Matrix.getTranslateInstance(0, pageSize.getHeight() - stringHeight / 1000f * 4));
font = PDTrueTypeFont.load(doc, PDDocument.class.getResourceAsStream(
"/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"), WinAnsiEncoding.INSTANCE);
contentStream.setFont(font, FONT_SIZE);
contentStream.showText(message);
float wordSpacing = (pageSize.getWidth() * 1000f - stringWidth) / (parts.length - 1) / 1000;
// TrueType font with word spacing
contentStream.setTextMatrix(
Matrix.getTranslateInstance(0, pageSize.getHeight() - stringHeight / 1000f * 5));
font = PDTrueTypeFont.load(doc, PDDocument.class.getResourceAsStream(
"/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"), WinAnsiEncoding.INSTANCE);
contentStream.setFont(font, FONT_SIZE);
contentStream.setWordSpacing(wordSpacing);
contentStream.showText(message);
// Type0 font with word spacing that has no effect
contentStream.setTextMatrix(
Matrix.getTranslateInstance(0, pageSize.getHeight() - stringHeight / 1000f * 6));
font = PDType0Font.load(doc, PDDocument.class.getResourceAsStream(
"/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"));
contentStream.setFont(font, FONT_SIZE);
contentStream.setWordSpacing(wordSpacing);
contentStream.showText(message);
// Finish up.
contentStream.endText();
}
doc.save(outfile);
}
| 119
| 1,423
| 1,542
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/SuperimposePage.java
|
SuperimposePage
|
main
|
class SuperimposePage
{
private SuperimposePage()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
if (args.length != 2)
{
System.err.println("usage: " + SuperimposePage.class.getName() +
" <source-pdf> <dest-pdf>");
System.exit(1);
}
String sourcePath = args[0];
String destPath = args[1];
try (PDDocument sourceDoc = Loader.loadPDF(new File(sourcePath)))
{
int sourcePage = 1;
// create a new PDF and add a blank page
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// write some sample text to the new page
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
contents.beginText();
contents.setFont(new PDType1Font(FontName.HELVETICA_BOLD), 12);
contents.newLineAtOffset(2, PDRectangle.LETTER.getHeight() - 12);
contents.showText("Sample text");
contents.endText();
// Create a Form XObject from the source document using LayerUtility
LayerUtility layerUtility = new LayerUtility(doc);
PDFormXObject form = layerUtility.importPageAsForm(sourceDoc, sourcePage - 1);
// draw the full form
contents.drawForm(form);
// draw a scaled form
contents.saveGraphicsState();
Matrix matrix = Matrix.getScaleInstance(0.5f, 0.5f);
contents.transform(matrix);
contents.drawForm(form);
contents.restoreGraphicsState();
// draw a scaled and rotated form
contents.saveGraphicsState();
matrix.rotate(1.8 * Math.PI); // radians
contents.transform(matrix);
contents.drawForm(form);
contents.restoreGraphicsState();
}
doc.save(destPath);
}
}
| 55
| 521
| 576
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/UsingTextMatrix.java
|
UsingTextMatrix
|
doIt
|
class UsingTextMatrix
{
/**
* Constructor.
*/
public UsingTextMatrix()
{
}
/**
* creates a sample document with some text using a text matrix.
*
* @param message The message to write in the file.
* @param outfile The resulting PDF.
*
* @throws IOException If there is an error writing the data.
*/
public void doIt( String message, String outfile ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will create a PDF document with some examples how to use a text matrix.
*
* @param args Command line arguments.
*/
public static void main(String[] args) throws IOException
{
UsingTextMatrix app = new UsingTextMatrix();
if( args.length != 2 )
{
app.usage();
}
else
{
app.doIt( args[0], args[1] );
}
}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
System.err.println( "usage: " + this.getClass().getName() + " <Message> <output-file>" );
}
}
|
// the document
try (PDDocument doc = new PDDocument())
{
// Page 1
PDFont font = new PDType1Font(FontName.HELVETICA);
PDPage page = new PDPage(PDRectangle.A4);
doc.addPage(page);
float fontSize = 12.0f;
PDRectangle pageSize = page.getMediaBox();
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, AppendMode.OVERWRITE, false);
contentStream.setFont( font, fontSize );
contentStream.beginText();
// counterclockwise rotation
for (int i=0;i<8;i++)
{
contentStream.setTextMatrix(Matrix.getRotateInstance(i * Math.PI * 0.25,
centeredXPosition, pageSize.getHeight() - centeredYPosition));
contentStream.showText(message + " " + i);
}
// clockwise rotation
for (int i=0;i<8;i++)
{
contentStream.setTextMatrix(Matrix.getRotateInstance(-i*Math.PI*0.25,
centeredXPosition, centeredYPosition));
contentStream.showText(message + " " + i);
}
contentStream.endText();
contentStream.close();
// Page 2
page = new PDPage(PDRectangle.A4);
doc.addPage(page);
fontSize = 1.0f;
contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
contentStream.setFont( font, fontSize );
contentStream.beginText();
// text scaling and translation
for (int i=0;i<10;i++)
{
contentStream.setTextMatrix(new Matrix(12f + (i * 6), 0, 0, 12f + (i * 6),
100, 100f + i * 50));
contentStream.showText(message + " " + i);
}
contentStream.endText();
contentStream.close();
// Page 3
page = new PDPage(PDRectangle.A4);
doc.addPage(page);
fontSize = 1.0f;
contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false);
contentStream.setFont( font, fontSize );
contentStream.beginText();
int i = 0;
// text scaling combined with rotation
contentStream.setTextMatrix(new Matrix(12, 0, 0, 12, centeredXPosition, centeredYPosition*1.5f));
contentStream.showText(message + " " + i++);
contentStream.setTextMatrix(new Matrix(0, 18, -18, 0, centeredXPosition, centeredYPosition*1.5f));
contentStream.showText(message + " " + i++);
contentStream.setTextMatrix(new Matrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition*1.5f));
contentStream.showText(message + " " + i++);
contentStream.setTextMatrix(new Matrix(0, -30, 30, 0, centeredXPosition, centeredYPosition*1.5f));
contentStream.showText(message + " " + i++);
contentStream.endText();
contentStream.close();
doc.save( outfile );
}
| 319
| 985
| 1,304
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/printing/OpaquePDFRenderer.java
|
OpaqueDrawObject
|
process
|
class OpaqueDrawObject extends GraphicsOperatorProcessor
{
public OpaqueDrawObject(PDFGraphicsStreamEngine context)
{
super(context);
}
private static final Logger LOG = LogManager.getLogger(OpaqueDrawObject.class);
@Override
public void process(Operator operator, List<COSBase> operands) throws IOException
{<FILL_FUNCTION_BODY>}
@Override
public String getName()
{
return OperatorName.DRAW_OBJECT;
}
}
|
if (operands.isEmpty())
{
throw new MissingOperandException(operator, operands);
}
COSBase base0 = operands.get(0);
if (!(base0 instanceof COSName))
{
return;
}
COSName objectName = (COSName) base0;
PDFGraphicsStreamEngine context = getGraphicsContext();
PDXObject xobject = context.getResources().getXObject(objectName);
if (xobject == null)
{
throw new MissingResourceException("Missing XObject: " + objectName.getName());
}
else if (xobject instanceof PDImageXObject)
{
PDImageXObject image = (PDImageXObject) xobject;
context.drawImage(image);
}
else if (xobject instanceof PDFormXObject)
{
try
{
context.increaseLevel();
if (context.getLevel() > 50)
{
LOG.error("recursion is too deep, skipping form XObject");
return;
}
context.showForm((PDFormXObject) xobject);
}
finally
{
context.decreaseLevel();
}
}
| 140
| 314
| 454
|
<methods>public void <init>(org.apache.pdfbox.pdmodel.PDDocument) ,public org.apache.pdfbox.pdmodel.interactive.annotation.AnnotationFilter getAnnotationsFilter() ,public org.apache.pdfbox.rendering.RenderDestination getDefaultDestination() ,public float getImageDownscalingOptimizationThreshold() ,public java.awt.RenderingHints getRenderingHints() ,public boolean isGroupEnabled(org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup) ,public boolean isSubsamplingAllowed() ,public java.awt.image.BufferedImage renderImage(int) throws java.io.IOException,public java.awt.image.BufferedImage renderImage(int, float) throws java.io.IOException,public java.awt.image.BufferedImage renderImage(int, float, org.apache.pdfbox.rendering.ImageType) throws java.io.IOException,public java.awt.image.BufferedImage renderImage(int, float, org.apache.pdfbox.rendering.ImageType, org.apache.pdfbox.rendering.RenderDestination) throws java.io.IOException,public java.awt.image.BufferedImage renderImageWithDPI(int, float) throws java.io.IOException,public java.awt.image.BufferedImage renderImageWithDPI(int, float, org.apache.pdfbox.rendering.ImageType) throws java.io.IOException,public void renderPageToGraphics(int, java.awt.Graphics2D) throws java.io.IOException,public void renderPageToGraphics(int, java.awt.Graphics2D, float) throws java.io.IOException,public void renderPageToGraphics(int, java.awt.Graphics2D, float, float) throws java.io.IOException,public void renderPageToGraphics(int, java.awt.Graphics2D, float, float, org.apache.pdfbox.rendering.RenderDestination) throws java.io.IOException,public void setAnnotationsFilter(org.apache.pdfbox.pdmodel.interactive.annotation.AnnotationFilter) ,public void setDefaultDestination(org.apache.pdfbox.rendering.RenderDestination) ,public void setImageDownscalingOptimizationThreshold(float) ,public void setRenderingHints(java.awt.RenderingHints) ,public void setSubsamplingAllowed(boolean) <variables>private org.apache.pdfbox.pdmodel.interactive.annotation.AnnotationFilter annotationFilter,private org.apache.pdfbox.rendering.RenderDestination defaultDestination,protected final non-sealed org.apache.pdfbox.pdmodel.PDDocument document,private float imageDownscalingOptimizationThreshold,private java.awt.image.BufferedImage pageImage,private final non-sealed org.apache.pdfbox.pdmodel.PDPageTree pageTree,private java.awt.RenderingHints renderingHints,private boolean subsamplingAllowed
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/printing/Printing.java
|
Printing
|
main
|
class Printing
{
private Printing()
{
}
/**
* Entry point.
*/
public static void main(String[] args) throws PrinterException, IOException
{<FILL_FUNCTION_BODY>}
/**
* Prints the document at its actual size. This is the recommended way to print.
*/
private static void print(PDDocument document) throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
job.print();
}
/**
* Prints using custom PrintRequestAttribute values.
*/
private static void printWithAttributes(PDDocument document) throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(new PageRanges(1, 1)); // pages 1 to 1
job.print(attr);
}
/**
* Prints with a print preview dialog.
*/
private static void printWithDialog(PDDocument document) throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
if (job.printDialog())
{
job.print();
}
}
/**
* Prints with a print preview dialog and custom PrintRequestAttribute values.
*/
private static void printWithDialogAndAttributes(PDDocument document) throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
attr.add(new PageRanges(1, 1)); // pages 1 to 1
PDViewerPreferences vp = document.getDocumentCatalog().getViewerPreferences();
if (vp != null && vp.getDuplex() != null)
{
String dp = vp.getDuplex();
if (PDViewerPreferences.DUPLEX.DuplexFlipLongEdge.toString().equals(dp))
{
attr.add(Sides.TWO_SIDED_LONG_EDGE);
}
else if (PDViewerPreferences.DUPLEX.DuplexFlipShortEdge.toString().equals(dp))
{
attr.add(Sides.TWO_SIDED_SHORT_EDGE);
}
else if (PDViewerPreferences.DUPLEX.Simplex.toString().equals(dp))
{
attr.add(Sides.ONE_SIDED);
}
}
if (job.printDialog(attr))
{
job.print(attr);
}
}
/**
* Prints using a custom page size and custom margins.
*/
private static void printWithPaper(PDDocument document) throws PrinterException
{
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
// define custom paper
Paper paper = new Paper();
paper.setSize(306, 396); // 1/72 inch
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight()); // no margins
// custom page format
PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);
// override the page format
Book book = new Book();
// append all pages
book.append(new PDFPrintable(document), pageFormat, document.getNumberOfPages());
job.setPageable(book);
job.print();
}
}
|
if (args.length != 1)
{
System.err.println("usage: java " + Printing.class.getName() + " <input>");
System.exit(1);
}
String filename = args[0];
try (PDDocument document = Loader.loadPDF(new File(filename)))
{
// choose your printing method:
print(document);
//printWithAttributes(document);
//printWithDialog(document);
//printWithDialogAndAttributes(document);
//printWithPaper(document);
}
| 982
| 143
| 1,125
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomGraphicsStreamEngine.java
|
CustomGraphicsStreamEngine
|
curveTo
|
class CustomGraphicsStreamEngine extends PDFGraphicsStreamEngine
{
/**
* Constructor.
*
* @param page PDF Page
*/
protected CustomGraphicsStreamEngine(PDPage page)
{
super(page);
}
public static void main(String[] args) throws IOException
{
File file = new File("src/main/resources/org/apache/pdfbox/examples/rendering/",
"custom-render-demo.pdf");
try (PDDocument doc = Loader.loadPDF(file))
{
PDPage page = doc.getPage(0);
CustomGraphicsStreamEngine engine = new CustomGraphicsStreamEngine(page);
engine.run();
}
}
/**
* Runs the engine on the current page.
*
* @throws IOException If there is an IO error while drawing the page.
*/
public void run() throws IOException
{
processPage(getPage());
for (PDAnnotation annotation : getPage().getAnnotations())
{
showAnnotation(annotation);
}
}
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) throws IOException
{
System.out.printf("appendRectangle %.2f %.2f, %.2f %.2f, %.2f %.2f, %.2f %.2f%n",
p0.getX(), p0.getY(), p1.getX(), p1.getY(),
p2.getX(), p2.getY(), p3.getX(), p3.getY());
}
@Override
public void drawImage(PDImage pdImage) throws IOException
{
System.out.println("drawImage");
}
@Override
public void clip(int windingRule) throws IOException
{
System.out.println("clip");
}
@Override
public void moveTo(float x, float y) throws IOException
{
System.out.printf("moveTo %.2f %.2f%n", x, y);
}
@Override
public void lineTo(float x, float y) throws IOException
{
System.out.printf("lineTo %.2f %.2f%n", x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) throws IOException
{<FILL_FUNCTION_BODY>}
@Override
public Point2D getCurrentPoint() throws IOException
{
// if you want to build paths, you'll need to keep track of this like PageDrawer does
return new Point2D.Float(0, 0);
}
@Override
public void closePath() throws IOException
{
System.out.println("closePath");
}
@Override
public void endPath() throws IOException
{
System.out.println("endPath");
}
@Override
public void strokePath() throws IOException
{
System.out.println("strokePath");
}
@Override
public void fillPath(int windingRule) throws IOException
{
System.out.println("fillPath");
}
@Override
public void fillAndStrokePath(int windingRule) throws IOException
{
System.out.println("fillAndStrokePath");
}
@Override
public void shadingFill(COSName shadingName) throws IOException
{
System.out.println("shadingFill " + shadingName.toString());
}
/**
* Overridden from PDFStreamEngine.
*/
@Override
public void showTextString(byte[] string) throws IOException
{
System.out.print("showTextString \"");
super.showTextString(string);
System.out.println("\"");
}
/**
* Overridden from PDFStreamEngine.
*/
@Override
public void showTextStrings(COSArray array) throws IOException
{
System.out.print("showTextStrings \"");
super.showTextStrings(array);
System.out.println("\"");
}
/**
* Overridden from PDFStreamEngine.
*/
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code, Vector displacement)
throws IOException
{
System.out.print("showGlyph " + code);
super.showGlyph(textRenderingMatrix, font, code, displacement);
}
// NOTE: there are may more methods in PDFStreamEngine which can be overridden here too.
}
|
System.out.printf("curveTo %.2f %.2f, %.2f %.2f, %.2f %.2f%n", x1, y1, x2, y2, x3, y3);
| 1,195
| 61
| 1,256
|
<methods>public abstract void appendRectangle(java.awt.geom.Point2D, java.awt.geom.Point2D, java.awt.geom.Point2D, java.awt.geom.Point2D) throws java.io.IOException,public abstract void clip(int) throws java.io.IOException,public abstract void closePath() throws java.io.IOException,public abstract void curveTo(float, float, float, float, float, float) throws java.io.IOException,public abstract void drawImage(org.apache.pdfbox.pdmodel.graphics.image.PDImage) throws java.io.IOException,public abstract void endPath() throws java.io.IOException,public abstract void fillAndStrokePath(int) throws java.io.IOException,public abstract void fillPath(int) throws java.io.IOException,public abstract java.awt.geom.Point2D getCurrentPoint() throws java.io.IOException,public abstract void lineTo(float, float) throws java.io.IOException,public abstract void moveTo(float, float) throws java.io.IOException,public abstract void shadingFill(org.apache.pdfbox.cos.COSName) throws java.io.IOException,public abstract void strokePath() throws java.io.IOException<variables>private final non-sealed org.apache.pdfbox.pdmodel.PDPage page
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomPageDrawer.java
|
MyPageDrawer
|
showGlyph
|
class MyPageDrawer extends PageDrawer
{
MyPageDrawer(PageDrawerParameters parameters) throws IOException
{
super(parameters);
}
/**
* Color replacement.
*/
@Override
protected Paint getPaint(PDColor color) throws IOException
{
// if this is the non-stroking color, find red, ignoring alpha channel
if (!(color.getColorSpace() instanceof PDPattern) &&
getGraphicsState().getNonStrokingColor() == color &&
color.toRGB() == (Color.RED.getRGB() & 0x00FFFFFF))
{
// replace it with blue
return Color.BLUE;
}
return super.getPaint(color);
}
/**
* Glyph bounding boxes.
*/
@Override
protected void showGlyph(Matrix textRenderingMatrix, PDFont font, int code,
Vector displacement) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Filled path bounding boxes.
*/
@Override
public void fillPath(int windingRule) throws IOException
{
// bbox in user units
Shape bbox = getLinePath().getBounds2D();
// draw path (note that getLinePath() is now reset)
super.fillPath(windingRule);
// save
Graphics2D graphics = getGraphics();
Color color = graphics.getColor();
Stroke stroke = graphics.getStroke();
Shape clip = graphics.getClip();
// draw
graphics.setClip(graphics.getDeviceConfiguration().getBounds());
graphics.setColor(Color.GREEN);
graphics.setStroke(new BasicStroke(.5f));
graphics.draw(bbox);
// restore
graphics.setStroke(stroke);
graphics.setColor(color);
graphics.setClip(clip);
}
/**
* Custom annotation rendering.
*/
@Override
public void showAnnotation(PDAnnotation annotation) throws IOException
{
// save
saveGraphicsState();
// 35% alpha
getGraphicsState().setNonStrokeAlphaConstant(0.35);
super.showAnnotation(annotation);
// restore
restoreGraphicsState();
}
}
|
// draw glyph
super.showGlyph(textRenderingMatrix, font, code, displacement);
// bbox in EM -> user units
Shape bbox = new Rectangle2D.Float(0, 0, font.getWidth(code) / 1000, 1);
AffineTransform at = textRenderingMatrix.createAffineTransform();
bbox = at.createTransformedShape(bbox);
// save
Graphics2D graphics = getGraphics();
Color color = graphics.getColor();
Stroke stroke = graphics.getStroke();
Shape clip = graphics.getClip();
// draw
graphics.setClip(graphics.getDeviceConfiguration().getBounds());
graphics.setColor(Color.RED);
graphics.setStroke(new BasicStroke(.5f));
graphics.draw(bbox);
// restore
graphics.setStroke(stroke);
graphics.setColor(color);
graphics.setClip(clip);
| 593
| 256
| 849
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/CMSProcessableInputStream.java
|
CMSProcessableInputStream
|
write
|
class CMSProcessableInputStream implements CMSTypedData
{
private final InputStream in;
private final ASN1ObjectIdentifier contentType;
CMSProcessableInputStream(InputStream is)
{
this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), is);
}
CMSProcessableInputStream(ASN1ObjectIdentifier type, InputStream is)
{
contentType = type;
in = is;
}
@Override
public Object getContent()
{
return in;
}
@Override
public void write(OutputStream out) throws IOException, CMSException
{<FILL_FUNCTION_BODY>}
@Override
public ASN1ObjectIdentifier getContentType()
{
return contentType;
}
}
|
// read the content only one time
in.transferTo(out);
in.close();
| 235
| 32
| 267
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateEmbeddedTimeStamp.java
|
CreateEmbeddedTimeStamp
|
embedTimeStamp
|
class CreateEmbeddedTimeStamp
{
private final String tsaUrl;
private PDDocument document;
private PDSignature signature;
private byte[] changedEncodedSignature;
public CreateEmbeddedTimeStamp(String tsaUrl)
{
this.tsaUrl = tsaUrl;
}
/**
* Embeds the given PDF file with signed timestamp(s). Alters the original file on disk.
*
* @param file the PDF file to sign and to overwrite
* @throws IOException
* @throws URISyntaxException
*/
public void embedTimeStamp(File file) throws IOException, URISyntaxException
{
embedTimeStamp(file, file);
}
/**
* Embeds signed timestamp(s) into existing signatures of the given document
*
* @param inFile The pdf file possibly containing signatures
* @param outFile Where the changed document will be saved
* @throws IOException
* @throws URISyntaxException
*/
public void embedTimeStamp(File inFile, File outFile) throws IOException, URISyntaxException
{<FILL_FUNCTION_BODY>}
/**
* Processes the time-stamping of the signature.
*
* @param inFile The existing PDF file
* @param outFile Where the new file will be written to
* @throws IOException
* @throws URISyntaxException
*/
private void processTimeStamping(File inFile, File outFile) throws IOException, URISyntaxException
{
try
{
byte[] documentBytes = Files.readAllBytes(inFile.toPath());
processRelevantSignatures(documentBytes);
if (changedEncodedSignature == null)
{
throw new IllegalStateException("No signature");
}
try (FileOutputStream output = new FileOutputStream(outFile))
{
embedNewSignatureIntoDocument(documentBytes, output);
}
}
catch (IOException | NoSuchAlgorithmException | CMSException e)
{
throw new IOException(e);
}
}
/**
* Create changed Signature with embedded TimeStamp from TSA
*
* @param documentBytes byte[] of the input file
* @throws IOException
* @throws CMSException
* @throws NoSuchAlgorithmException
* @throws URISyntaxException
*/
private void processRelevantSignatures(byte[] documentBytes)
throws IOException, CMSException, NoSuchAlgorithmException, URISyntaxException
{
signature = SigUtils.getLastRelevantSignature(document);
if (signature == null)
{
return;
}
byte[] sigBlock = signature.getContents(documentBytes);
CMSSignedData signedData = new CMSSignedData(sigBlock);
System.out.println("INFO: Byte Range: " + Arrays.toString(signature.getByteRange()));
if (tsaUrl != null && !tsaUrl.isEmpty())
{
ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
signedData = validation.addSignedTimeStamp(signedData);
}
byte[] newEncoded = Hex.getBytes(signedData.getEncoded());
int maxSize = signature.getByteRange()[2] - signature.getByteRange()[1];
System.out.println(
"INFO: New Signature has Size: " + newEncoded.length + " maxSize: " + maxSize);
if (newEncoded.length > maxSize - 2)
{
throw new IOException(
"New Signature is too big for existing Signature-Placeholder. Max Place: "
+ maxSize);
}
else
{
changedEncodedSignature = newEncoded;
}
}
/**
* Embeds the new signature into the document, by copying the rest of the document
*
* @param docBytes byte array of the document
* @param output target, where the file will be written
* @throws IOException
*/
private void embedNewSignatureIntoDocument(byte[] docBytes, OutputStream output)
throws IOException
{
int[] byteRange = signature.getByteRange();
output.write(docBytes, byteRange[0], byteRange[1] + 1);
output.write(changedEncodedSignature);
int addingLength = byteRange[2] - byteRange[1] - 2 - changedEncodedSignature.length;
byte[] zeroes = Hex.getBytes(new byte[(addingLength + 1) / 2]);
output.write(zeroes);
output.write(docBytes, byteRange[2] - 1, byteRange[3] + 1);
}
public static void main(String[] args) throws IOException, URISyntaxException
{
if (args.length != 3)
{
usage();
System.exit(1);
}
String tsaUrl = null;
for (int i = 0; i < args.length; i++)
{
if ("-tsa".equals(args[i]))
{
i++;
if (i >= args.length)
{
usage();
System.exit(1);
}
tsaUrl = args[i];
}
}
File inFile = new File(args[0]);
System.out.println("Input File: " + args[0]);
String name = inFile.getName();
String substring = name.substring(0, name.lastIndexOf('.'));
File outFile = new File(inFile.getParent(), substring + "_eTs.pdf");
System.out.println("Output File: " + outFile.getAbsolutePath());
// Embed TimeStamp
CreateEmbeddedTimeStamp signing = new CreateEmbeddedTimeStamp(tsaUrl);
signing.embedTimeStamp(inFile, outFile);
}
private static void usage()
{
System.err.println("usage: java " + CreateEmbeddedTimeStamp.class.getName() + " "
+ "<pdf_to_sign>\n" + "mandatory option:\n"
+ " -tsa <url> sign timestamp using the given TSA server\n");
}
}
|
if (inFile == null || !inFile.exists())
{
throw new FileNotFoundException("Document for signing does not exist");
}
// sign
try (PDDocument doc = Loader.loadPDF(inFile))
{
document = doc;
processTimeStamping(inFile, outFile);
}
| 1,585
| 88
| 1,673
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateEmptySignatureForm.java
|
CreateEmptySignatureForm
|
main
|
class CreateEmptySignatureForm
{
private CreateEmptySignatureForm()
{
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
// Create a new document with an empty page.
try (PDDocument document = new PDDocument())
{
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
// Adobe Acrobat uses Helvetica as a default font and
// stores that under the name '/Helv' in the resources dictionary
PDFont font = new PDType1Font(FontName.HELVETICA);
PDResources resources = new PDResources();
resources.put(COSName.HELV, font);
// Add a new AcroForm and add that to the document
PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
// Add and set the resources and default appearance at the form level
acroForm.setDefaultResources(resources);
// Acrobat sets the font size on the form level to be
// auto sized as default. This is done by setting the font size to '0'
String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);
// --- end of general AcroForm stuff ---
// Create empty signature field, it will get the name "Signature1"
PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 650, 200, 50);
widget.setRectangle(rect);
widget.setPage(page);
// see thread from PDFBox users mailing list 17.2.2021 - 19.2.2021
// https://mail-archives.apache.org/mod_mbox/pdfbox-users/202102.mbox/thread
widget.setPrinted(true);
page.getAnnotations().add(widget);
acroForm.getFields().add(signatureField);
document.save(args[0]);
}
| 54
| 541
| 595
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignature.java
|
CreateSignature
|
main
|
class CreateSignature extends CreateSignatureBase
{
/**
* Initialize the signature creator with a keystore and certificate password.
*
* @param keystore the pkcs12 keystore containing the signing certificate
* @param pin the password for recovering the key
* @throws KeyStoreException if the keystore has not been initialized (loaded)
* @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
* @throws UnrecoverableKeyException if the given password is wrong
* @throws CertificateException if the certificate is not valid as signing time
* @throws IOException if no certificate could be found
*/
public CreateSignature(KeyStore keystore, char[] pin)
throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, IOException
{
super(keystore, pin);
}
/**
* Signs the given PDF file. Alters the original file on disk.
* @param file the PDF file to sign
* @throws IOException if the file could not be read or written
*/
public void signDetached(File file) throws IOException
{
signDetached(file, file, null);
}
/**
* Signs the given PDF file.
* @param inFile input PDF file
* @param outFile output PDF file
* @throws IOException if the input file could not be read
*/
public void signDetached(File inFile, File outFile) throws IOException
{
signDetached(inFile, outFile, null);
}
/**
* Signs the given PDF file.
* @param inFile input PDF file
* @param outFile output PDF file
* @param tsaUrl optional TSA url
* @throws IOException if the input file could not be read
*/
public void signDetached(File inFile, File outFile, String tsaUrl) throws IOException
{
if (inFile == null || !inFile.exists())
{
throw new FileNotFoundException("Document for signing does not exist");
}
setTsaUrl(tsaUrl);
// sign
try (FileOutputStream fos = new FileOutputStream(outFile);
PDDocument doc = Loader.loadPDF(inFile))
{
signDetached(doc, fos);
}
}
public void signDetached(PDDocument document, OutputStream output)
throws IOException
{
// call SigUtils.checkCrossReferenceTable(document) if Adobe complains
// and read https://stackoverflow.com/a/71293901/535646
// and https://issues.apache.org/jira/browse/PDFBOX-5382
int accessPermissions = SigUtils.getMDPPermission(document);
if (accessPermissions == 1)
{
throw new IllegalStateException("No changes to the document are permitted due to DocMDP transform parameters dictionary");
}
// create signature dictionary
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName("Example User");
signature.setLocation("Los Angeles, CA");
signature.setReason("Testing");
// TODO extract the above details from the signing certificate? Reason as a parameter?
// the signing date, needed for valid signature
signature.setSignDate(Calendar.getInstance());
// Optional: certify
if (accessPermissions == 0)
{
SigUtils.setMDPPermission(document, signature, 2);
}
if (isExternalSigning())
{
document.addSignature(signature);
ExternalSigningSupport externalSigning =
document.saveIncrementalForExternalSigning(output);
// invoke external signature service
byte[] cmsSignature = sign(externalSigning.getContent());
// set signature bytes received from the service
externalSigning.setSignature(cmsSignature);
}
else
{
SignatureOptions signatureOptions = new SignatureOptions();
// Size can vary, but should be enough for purpose.
signatureOptions.setPreferredSignatureSize(SignatureOptions.DEFAULT_SIGNATURE_SIZE * 2);
// register signature dictionary and sign interface
document.addSignature(signature, this, signatureOptions);
// write incremental (only for signing purpose)
document.saveIncremental(output);
}
}
public static void main(String[] args) throws IOException, GeneralSecurityException
{<FILL_FUNCTION_BODY>}
private static void usage()
{
System.err.println("usage: java " + CreateSignature.class.getName() + " " +
"<pkcs12_keystore> <password> <pdf_to_sign>\n" +
"options:\n" +
" -tsa <url> sign timestamp using the given TSA server\n" +
" -e sign using external signature creation scenario");
}
}
|
if (args.length < 3)
{
usage();
System.exit(1);
}
String tsaUrl = null;
boolean externalSig = false;
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("-tsa"))
{
i++;
if (i >= args.length)
{
usage();
System.exit(1);
}
tsaUrl = args[i];
}
if (args[i].equals("-e"))
{
externalSig = true;
}
}
// load the keystore
KeyStore keystore = KeyStore.getInstance("PKCS12");
char[] password = args[1].toCharArray(); // TODO use Java 6 java.io.Console.readPassword
try (InputStream is = new FileInputStream(args[0]))
{
keystore.load(is, password);
}
// TODO alias command line argument
// sign PDF
CreateSignature signing = new CreateSignature(keystore, password);
signing.setExternalSigning(externalSig);
File inFile = new File(args[2]);
String name = inFile.getName();
String substring = name.substring(0, name.lastIndexOf('.'));
File outFile = new File(inFile.getParent(), substring + "_signed.pdf");
signing.signDetached(inFile, outFile, tsaUrl);
| 1,289
| 382
| 1,671
|
<methods>public void <init>(java.security.KeyStore, char[]) throws java.security.KeyStoreException, java.security.UnrecoverableKeyException, java.security.NoSuchAlgorithmException, java.io.IOException, java.security.cert.CertificateException,public java.security.cert.Certificate[] getCertificateChain() ,public boolean isExternalSigning() ,public final void setCertificateChain(java.security.cert.Certificate[]) ,public void setExternalSigning(boolean) ,public final void setPrivateKey(java.security.PrivateKey) ,public void setTsaUrl(java.lang.String) ,public byte[] sign(java.io.InputStream) throws java.io.IOException<variables>private java.security.cert.Certificate[] certificateChain,private boolean externalSigning,private java.security.PrivateKey privateKey,private java.lang.String tsaUrl
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignatureBase.java
|
CreateSignatureBase
|
sign
|
class CreateSignatureBase implements SignatureInterface
{
private PrivateKey privateKey;
private Certificate[] certificateChain;
private String tsaUrl;
private boolean externalSigning;
/**
* Initialize the signature creator with a keystore (pkcs12) and pin that should be used for the
* signature.
*
* @param keystore is a pkcs12 keystore.
* @param pin is the pin for the keystore / private key
* @throws KeyStoreException if the keystore has not been initialized (loaded)
* @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
* @throws UnrecoverableKeyException if the given password is wrong
* @throws CertificateException if the certificate is not valid as signing time
* @throws IOException if no certificate could be found
*/
public CreateSignatureBase(KeyStore keystore, char[] pin)
throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException
{
// grabs the first alias from the keystore and get the private key. An
// alternative method or constructor could be used for setting a specific
// alias that should be used.
Enumeration<String> aliases = keystore.aliases();
String alias;
Certificate cert = null;
while (cert == null && aliases.hasMoreElements())
{
alias = aliases.nextElement();
setPrivateKey((PrivateKey) keystore.getKey(alias, pin));
Certificate[] certChain = keystore.getCertificateChain(alias);
if (certChain != null)
{
setCertificateChain(certChain);
cert = certChain[0];
if (cert instanceof X509Certificate)
{
// avoid expired certificate
((X509Certificate) cert).checkValidity();
SigUtils.checkCertificateUsage((X509Certificate) cert);
}
}
}
if (cert == null)
{
throw new IOException("Could not find certificate");
}
}
public final void setPrivateKey(PrivateKey privateKey)
{
this.privateKey = privateKey;
}
public final void setCertificateChain(final Certificate[] certificateChain)
{
this.certificateChain = certificateChain;
}
public Certificate[] getCertificateChain()
{
return certificateChain;
}
public void setTsaUrl(String tsaUrl)
{
this.tsaUrl = tsaUrl;
}
/**
* SignatureInterface sample implementation.
*<p>
* This method will be called from inside of the pdfbox and create the PKCS #7 signature.
* The given InputStream contains the bytes that are given by the byte range.
*<p>
* This method is for internal use only.
*<p>
* Use your favorite cryptographic library to implement PKCS #7 signature creation.
* If you want to create the hash and the signature separately (e.g. to transfer only the hash
* to an external application), read <a href="https://stackoverflow.com/questions/41767351">this
* answer</a> or <a href="https://stackoverflow.com/questions/56867465">this answer</a>.
*
* @throws IOException
*/
@Override
public byte[] sign(InputStream content) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Set if external signing scenario should be used.
* If {@code false}, SignatureInterface would be used for signing.
* <p>
* Default: {@code false}
* </p>
* @param externalSigning {@code true} if external signing should be performed
*/
public void setExternalSigning(boolean externalSigning)
{
this.externalSigning = externalSigning;
}
public boolean isExternalSigning()
{
return externalSigning;
}
}
|
// cannot be done private (interface)
try
{
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
X509Certificate cert = (X509Certificate) certificateChain[0];
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, cert));
gen.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
CMSSignedData signedData = gen.generate(msg, false);
if (tsaUrl != null && !tsaUrl.isEmpty())
{
ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
signedData = validation.addSignedTimeStamp(signedData);
}
return signedData.getEncoded();
}
catch (GeneralSecurityException | CMSException | OperatorCreationException | URISyntaxException e)
{
throw new IOException(e);
}
| 1,025
| 302
| 1,327
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignedTimeStamp.java
|
CreateSignedTimeStamp
|
main
|
class CreateSignedTimeStamp implements SignatureInterface
{
private static final Logger LOG = LogManager.getLogger(CreateSignedTimeStamp.class);
private final String tsaUrl;
/**
* Initialize the signed timestamp creator
*
* @param tsaUrl The url where TS-Request will be done.
*/
public CreateSignedTimeStamp(String tsaUrl)
{
this.tsaUrl = tsaUrl;
}
/**
* Signs the given PDF file. Alters the original file on disk.
*
* @param file the PDF file to sign
* @throws IOException if the file could not be read or written
*/
public void signDetached(File file) throws IOException
{
signDetached(file, file);
}
/**
* Signs the given PDF file.
*
* @param inFile input PDF file
* @param outFile output PDF file
* @throws IOException if the input file could not be read
*/
public void signDetached(File inFile, File outFile) throws IOException
{
if (inFile == null || !inFile.exists())
{
throw new FileNotFoundException("Document for signing does not exist");
}
// sign
try (PDDocument doc = Loader.loadPDF(inFile);
FileOutputStream fos = new FileOutputStream(outFile))
{
signDetached(doc, fos);
}
}
/**
* Prepares the TimeStamp-Signature and starts the saving-process.
*
* @param document given Pdf
* @param output Where the file will be written
* @throws IOException
*/
public void signDetached(PDDocument document, OutputStream output) throws IOException
{
int accessPermissions = SigUtils.getMDPPermission(document);
if (accessPermissions == 1)
{
throw new IllegalStateException(
"No changes to the document are permitted due to DocMDP transform parameters dictionary");
}
// create signature dictionary
PDSignature signature = new PDSignature();
signature.setType(COSName.DOC_TIME_STAMP);
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(COSName.getPDFName("ETSI.RFC3161"));
// No certification allowed because /Reference not allowed in signature directory
// see ETSI EN 319 142-1 Part 1 and ETSI TS 102 778-4
// http://www.etsi.org/deliver/etsi_en%5C319100_319199%5C31914201%5C01.01.00_30%5Cen_31914201v010100v.pdf
// http://www.etsi.org/deliver/etsi_ts/102700_102799/10277804/01.01.01_60/ts_10277804v010101p.pdf
// register signature dictionary and sign interface
document.addSignature(signature, this);
// write incremental (only for signing purpose)
document.saveIncremental(output);
}
@Override
public byte[] sign(InputStream content) throws IOException
{
ValidationTimeStamp validation;
try
{
validation = new ValidationTimeStamp(tsaUrl);
return validation.getTimeStampToken(content);
}
catch (NoSuchAlgorithmException | URISyntaxException e)
{
LOG.error("Hashing-Algorithm not found for TimeStamping", e);
}
return new byte[] {};
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static void usage()
{
System.err.println("usage: java " + CreateSignedTimeStamp.class.getName() + " "
+ "<pdf_to_sign>\n" + "mandatory options:\n"
+ " -tsa <url> sign timestamp using the given TSA server\n");
}
}
|
if (args.length != 3)
{
usage();
System.exit(1);
}
String tsaUrl = null;
if ("-tsa".equals(args[1]))
{
tsaUrl = args[2];
}
else
{
usage();
System.exit(1);
}
// sign PDF
CreateSignedTimeStamp signing = new CreateSignedTimeStamp(tsaUrl);
File inFile = new File(args[0]);
String name = inFile.getName();
String substring = name.substring(0, name.lastIndexOf('.'));
File outFile = new File(inFile.getParent(), substring + "_timestamped.pdf");
signing.signDetached(inFile, outFile);
| 1,097
| 204
| 1,301
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/TSAClient.java
|
TSAClient
|
getTSAResponse
|
class TSAClient
{
private static final Logger LOG = LogManager.getLogger(TSAClient.class);
private static final DigestAlgorithmIdentifierFinder ALGORITHM_OID_FINDER =
new DefaultDigestAlgorithmIdentifierFinder();
private final URL url;
private final String username;
private final String password;
private final MessageDigest digest;
// SecureRandom.getInstanceStrong() would be better, but sometimes blocks on Linux
private static final Random RANDOM = new SecureRandom();
/**
*
* @param url the URL of the TSA service
* @param username user name of TSA
* @param password password of TSA
* @param digest the message digest to use
*/
public TSAClient(URL url, String username, String password, MessageDigest digest)
{
this.url = url;
this.username = username;
this.password = password;
this.digest = digest;
}
/**
*
* @param content
* @return the time stamp token
* @throws IOException if there was an error with the connection or data from the TSA server,
* or if the time stamp response could not be validated
*/
public TimeStampToken getTimeStampToken(InputStream content) throws IOException
{
digest.reset();
DigestInputStream dis = new DigestInputStream(content, digest);
while (dis.read() != -1)
{
// do nothing
}
byte[] hash = digest.digest();
// 32-bit cryptographic nonce
int nonce = RANDOM.nextInt();
// generate TSA request
TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
tsaGenerator.setCertReq(true);
ASN1ObjectIdentifier oid = ALGORITHM_OID_FINDER.find(digest.getAlgorithm()).getAlgorithm();
TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));
// get TSA response
byte[] tsaResponse = getTSAResponse(request.getEncoded());
TimeStampResponse response;
try
{
response = new TimeStampResponse(tsaResponse);
response.validate(request);
}
catch (TSPException e)
{
throw new IOException(e);
}
TimeStampToken timeStampToken = response.getTimeStampToken();
if (timeStampToken == null)
{
// https://www.ietf.org/rfc/rfc3161.html#section-2.4.2
throw new IOException("Response from " + url +
" does not have a time stamp token, status: " + response.getStatus() +
" (" + response.getStatusString() + ")");
}
return timeStampToken;
}
// gets response data for the given encoded TimeStampRequest data
// throws IOException if a connection to the TSA cannot be established
private byte[] getTSAResponse(byte[] request) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
LOG.debug("Opening connection to TSA server");
// todo: support proxy servers
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/timestamp-query");
LOG.debug("Established connection to TSA server");
if (username != null && password != null && !username.isEmpty() && !password.isEmpty())
{
String contentEncoding = connection.getContentEncoding();
if (contentEncoding == null)
{
contentEncoding = StandardCharsets.UTF_8.name();
}
connection.setRequestProperty("Authorization",
"Basic " + new String(Base64.getEncoder().encode((username + ":" + password).
getBytes(contentEncoding))));
}
// read response
try (OutputStream output = connection.getOutputStream())
{
output.write(request);
}
catch (IOException ex)
{
LOG.error("Exception when writing to {}", this.url, ex);
throw ex;
}
LOG.debug("Waiting for response from TSA server");
byte[] response;
try (InputStream input = connection.getInputStream())
{
response = input.readAllBytes();
}
catch (IOException ex)
{
LOG.error("Exception when reading from {}", this.url, ex);
throw ex;
}
LOG.debug("Received response from TSA server");
return response;
| 884
| 439
| 1,323
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/ValidationTimeStamp.java
|
ValidationTimeStamp
|
signTimeStamp
|
class ValidationTimeStamp
{
private TSAClient tsaClient;
/**
* @param tsaUrl The url where TS-Request will be done.
* @throws NoSuchAlgorithmException
* @throws MalformedURLException
* @throws java.net.URISyntaxException
*/
public ValidationTimeStamp(String tsaUrl)
throws NoSuchAlgorithmException, MalformedURLException, URISyntaxException
{
if (tsaUrl != null)
{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
this.tsaClient = new TSAClient(new URI(tsaUrl).toURL(), null, null, digest);
}
}
/**
* Creates a signed timestamp token by the given input stream.
*
* @param content InputStream of the content to sign
* @return the byte[] of the timestamp token
* @throws IOException
*/
public byte[] getTimeStampToken(InputStream content) throws IOException
{
TimeStampToken timeStampToken = tsaClient.getTimeStampToken(content);
return timeStampToken.getEncoded();
}
/**
* Extend cms signed data with TimeStamp first or to all signers
*
* @param signedData Generated CMS signed data
* @return CMSSignedData Extended CMS signed data
* @throws IOException
*/
public CMSSignedData addSignedTimeStamp(CMSSignedData signedData)
throws IOException
{
SignerInformationStore signerStore = signedData.getSignerInfos();
List<SignerInformation> newSigners = new ArrayList<>();
for (SignerInformation signer : signerStore.getSigners())
{
// This adds a timestamp to every signer (into his unsigned attributes) in the signature.
newSigners.add(signTimeStamp(signer));
}
// Because new SignerInformation is created, new SignerInfoStore has to be created
// and also be replaced in signedData. Which creates a new signedData object.
return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}
/**
* Extend CMS Signer Information with the TimeStampToken into the unsigned Attributes.
*
* @param signer information about signer
* @return information about SignerInformation
* @throws IOException
*/
private SignerInformation signTimeStamp(SignerInformation signer)
throws IOException
{<FILL_FUNCTION_BODY>}
}
|
AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
ASN1EncodableVector vector = new ASN1EncodableVector();
if (unsignedAttributes != null)
{
vector = unsignedAttributes.toASN1EncodableVector();
}
TimeStampToken timeStampToken = tsaClient.getTimeStampToken(
new ByteArrayInputStream(signer.getSignature()));
byte[] token = timeStampToken.getEncoded();
ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
ASN1Encodable signatureTimeStamp = new Attribute(oid,
new DERSet(ASN1Primitive.fromByteArray(token)));
vector.add(signatureTimeStamp);
Attributes signedAttributes = new Attributes(vector);
// There is no other way changing the unsigned attributes of the signer information.
// result is never null, new SignerInformation always returned,
// see source code of replaceUnsignedAttributes
return SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(signedAttributes));
| 649
| 283
| 932
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/signature/validation/CertInformationHelper.java
|
CertInformationHelper
|
extractCrlUrlFromSequence
|
class CertInformationHelper
{
private static final Logger LOG = LogManager.getLogger(CertInformationHelper.class);
private CertInformationHelper()
{
}
/**
* Gets the SHA-1-Hash has of given byte[]-content.
*
* @param content to be hashed
* @return SHA-1 hash String
*/
protected static String getSha1Hash(byte[] content)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
return Hex.getString(md.digest(content));
}
catch (NoSuchAlgorithmException e)
{
LOG.error("No SHA-1 Algorithm found", e);
}
return null;
}
/**
* Extracts authority information access extension values from the given data. The Data
* structure has to be implemented as described in RFC 2459, 4.2.2.1.
*
* @param extensionValue byte[] of the extension value.
* @param certInfo where to put the found values
* @throws IOException when there is a problem with the extensionValue
*/
protected static void getAuthorityInfoExtensionValue(byte[] extensionValue,
CertSignatureInformation certInfo) throws IOException
{
ASN1Sequence asn1Seq = (ASN1Sequence) JcaX509ExtensionUtils.parseExtensionValue(extensionValue);
Enumeration<?> objects = asn1Seq.getObjects();
while (objects.hasMoreElements())
{
// AccessDescription
ASN1Sequence obj = (ASN1Sequence) objects.nextElement();
ASN1Encodable oid = obj.getObjectAt(0);
// accessLocation
ASN1TaggedObject location = (ASN1TaggedObject) obj.getObjectAt(1);
if (X509ObjectIdentifiers.id_ad_ocsp.equals(oid)
&& location.getTagNo() == GeneralName.uniformResourceIdentifier)
{
ASN1OctetString url = (ASN1OctetString) location.getBaseObject();
certInfo.setOcspUrl(new String(url.getOctets()));
}
else if (X509ObjectIdentifiers.id_ad_caIssuers.equals(oid))
{
ASN1OctetString uri = (ASN1OctetString) location.getBaseObject();
certInfo.setIssuerUrl(new String(uri.getOctets()));
}
}
}
/**
* Gets the first CRL URL from given extension value. Structure has to be
* built as in 4.2.1.14 CRL Distribution Points of RFC 2459.
*
* @param extensionValue to get the extension value from
* @return first CRL- URL or null
* @throws IOException when there is a problem with the extensionValue
*/
protected static String getCrlUrlFromExtensionValue(byte[] extensionValue) throws IOException
{
ASN1Sequence asn1Seq = (ASN1Sequence) JcaX509ExtensionUtils.parseExtensionValue(extensionValue);
Enumeration<?> objects = asn1Seq.getObjects();
while (objects.hasMoreElements())
{
Object obj = objects.nextElement();
if (obj instanceof ASN1Sequence)
{
String url = extractCrlUrlFromSequence((ASN1Sequence) obj);
if (url != null)
{
return url;
}
}
}
return null;
}
private static String extractCrlUrlFromSequence(ASN1Sequence sequence)
{<FILL_FUNCTION_BODY>}
}
|
ASN1TaggedObject taggedObject = (ASN1TaggedObject) sequence.getObjectAt(0);
taggedObject = (ASN1TaggedObject) taggedObject.getBaseObject();
if (taggedObject.getBaseObject() instanceof ASN1TaggedObject)
{
taggedObject = (ASN1TaggedObject) taggedObject.getBaseObject();
}
else if (taggedObject.getBaseObject() instanceof ASN1Sequence)
{
// multiple URLs (we take the first)
ASN1Sequence seq = (ASN1Sequence) taggedObject.getBaseObject();
if (seq.getObjectAt(0) instanceof ASN1TaggedObject)
{
taggedObject = (ASN1TaggedObject) seq.getObjectAt(0);
}
else
{
return null;
}
}
else
{
return null;
}
if (taggedObject.getBaseObject() instanceof ASN1OctetString)
{
ASN1OctetString uri = (ASN1OctetString) taggedObject.getBaseObject();
String url = new String(uri.getOctets());
// return first http(s)-Url for crl
if (url.startsWith("http"))
{
return url;
}
}
// else happens with http://blogs.adobe.com/security/SampleSignedPDFDocument.pdf
return null;
| 936
| 363
| 1,299
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/AddWatermarkText.java
|
AddWatermarkText
|
addWatermarkText
|
class AddWatermarkText
{
private AddWatermarkText()
{
}
public static void main(String[] args) throws IOException
{
if (args.length != 3)
{
usage();
}
else
{
File srcFile = new File(args[0]);
File dstFile = new File(args[1]);
String text = args[2];
try (PDDocument doc = Loader.loadPDF(srcFile))
{
for (PDPage page : doc.getPages())
{
PDFont font = new PDType1Font(FontName.HELVETICA);
addWatermarkText(doc, page, font, text);
}
doc.save(dstFile);
}
}
}
private static void addWatermarkText(PDDocument doc, PDPage page, PDFont font, String text)
throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage.
*/
private static void usage()
{
System.err.println("Usage: java " + AddWatermarkText.class.getName() + " <input-pdf> <output-pdf> <short text>");
}
}
|
try (PDPageContentStream cs
= new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true))
{
float fontHeight = 100; // arbitrary for short text
float width = page.getMediaBox().getWidth();
float height = page.getMediaBox().getHeight();
int rotation = page.getRotation();
switch (rotation)
{
case 90:
width = page.getMediaBox().getHeight();
height = page.getMediaBox().getWidth();
cs.transform(Matrix.getRotateInstance(Math.toRadians(90), height, 0));
break;
case 180:
cs.transform(Matrix.getRotateInstance(Math.toRadians(180), width, height));
break;
case 270:
width = page.getMediaBox().getHeight();
height = page.getMediaBox().getWidth();
cs.transform(Matrix.getRotateInstance(Math.toRadians(270), 0, width));
break;
default:
break;
}
float stringWidth = font.getStringWidth(text) / 1000 * fontHeight;
float diagonalLength = (float) Math.sqrt(width * width + height * height);
float angle = (float) Math.atan2(height, width);
float x = (diagonalLength - stringWidth) / 2; // "horizontal" position in rotated world
float y = -fontHeight / 4; // 4 is a trial-and-error thing, this lowers the text a bit
cs.transform(Matrix.getRotateInstance(angle, 0, 0));
cs.setFont(font, fontHeight);
// cs.setRenderingMode(RenderingMode.STROKE) // for "hollow" effect
PDExtendedGraphicsState gs = new PDExtendedGraphicsState();
gs.setNonStrokingAlphaConstant(0.2f);
gs.setStrokingAlphaConstant(0.2f);
gs.setBlendMode(BlendMode.MULTIPLY);
gs.setLineWidth(3f);
cs.setGraphicsStateParameters(gs);
cs.setNonStrokingColor(Color.red);
cs.setStrokingColor(Color.red);
cs.beginText();
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
}
| 320
| 652
| 972
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/ExtractTextByArea.java
|
ExtractTextByArea
|
main
|
class ExtractTextByArea
{
private ExtractTextByArea()
{
//utility class and should not be constructed.
}
/**
* This will print the documents text in a certain area.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + ExtractTextByArea.class.getName() + " <input-pdf>" );
}
}
|
if( args.length != 1 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition( true );
Rectangle rect = new Rectangle( 10, 280, 275, 60 );
stripper.addRegion( "class1", rect );
PDPage firstPage = document.getPage(0);
stripper.extractRegions( firstPage );
System.out.println( "Text in the area:" + rect );
System.out.println( stripper.getTextForRegion( "class1" ) );
}
}
| 187
| 205
| 392
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/ExtractTextSimple.java
|
ExtractTextSimple
|
main
|
class ExtractTextSimple
{
private ExtractTextSimple()
{
// example class should not be instantiated
}
/**
* This will print the documents text page by page.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing or extracting the document.
*/
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println("Usage: java " + ExtractTextSimple.class.getName() + " <input-pdf>");
System.exit(-1);
}
}
|
if (args.length != 1)
{
usage();
}
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
AccessPermission ap = document.getCurrentAccessPermission();
if (!ap.canExtractContent())
{
throw new IOException("You do not have permission to extract text");
}
PDFTextStripper stripper = new PDFTextStripper();
// This example uses sorting, but in some cases it is more useful to switch it off,
// e.g. in some files with columns where the PDF content stream respects the
// column order.
stripper.setSortByPosition(true);
for (int p = 1; p <= document.getNumberOfPages(); ++p)
{
// Set the page interval to extract. If you don't, then all pages would be extracted.
stripper.setStartPage(p);
stripper.setEndPage(p);
// let the magic happen
String text = stripper.getText(document);
// do some nice output with a header
String pageStr = String.format("page %d:", p);
System.out.println(pageStr);
for (int i = 0; i < pageStr.length(); ++i)
{
System.out.print("-");
}
System.out.println();
System.out.println(text.trim());
System.out.println();
// If the extracted text is empty or gibberish, please try extracting text
// with Adobe Reader first before asking for help. Also read the FAQ
// on the website:
// https://pdfbox.apache.org/2.0/faq.html#text-extraction
}
}
| 188
| 443
| 631
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/PDFHighlighter.java
|
PDFHighlighter
|
main
|
class PDFHighlighter extends PDFTextStripper
{
private Writer highlighterOutput = null;
private String[] searchedWords;
private ByteArrayOutputStream textOS = null;
private Writer textWriter = null;
private static final Charset ENCODING = StandardCharsets.UTF_16;
/**
* Default constructor.
*
* @throws IOException If there is an error constructing this class.
*/
public PDFHighlighter() throws IOException
{
super.setLineSeparator( "" );
super.setWordSeparator( "" );
super.setShouldSeparateByBeads( false );
super.setSuppressDuplicateOverlappingText( false );
}
/**
* Generate an XML highlight string based on the PDF.
*
* @param pdDocument The PDF to find words in.
* @param highlightWord The word to search for.
* @param xmlOutput The resulting output xml file.
*
* @throws IOException If there is an error reading from the PDF, or writing to the XML.
*/
public void generateXMLHighlight(PDDocument pdDocument, String highlightWord, Writer xmlOutput ) throws IOException
{
generateXMLHighlight( pdDocument, new String[] { highlightWord }, xmlOutput );
}
/**
* Generate an XML highlight string based on the PDF.
*
* @param pdDocument The PDF to find words in.
* @param sWords The words to search for.
* @param xmlOutput The resulting output xml file.
*
* @throws IOException If there is an error reading from the PDF, or writing to the XML.
*/
public void generateXMLHighlight(PDDocument pdDocument, String[] sWords, Writer xmlOutput ) throws IOException
{
highlighterOutput = xmlOutput;
searchedWords = sWords;
highlighterOutput.write("<XML>\n<Body units=characters " +
" version=2>\n<Highlight>\n");
textOS = new ByteArrayOutputStream();
textWriter = new OutputStreamWriter( textOS, ENCODING);
writeText(pdDocument, textWriter);
highlighterOutput.write("</Highlight>\n</Body>\n</XML>");
highlighterOutput.flush();
}
/**
* {@inheritDoc}
*/
@Override
protected void endPage( PDPage pdPage ) throws IOException
{
textWriter.flush();
String page = textOS.toString(ENCODING);
textOS.reset();
// Traitement des listes à puces (caractères spéciaux)
if (page.indexOf('a') != -1)
{
page = page.replaceAll("a[0-9]{1,3}", ".");
}
for (String searchedWord : searchedWords)
{
Pattern pattern = Pattern.compile(searchedWord, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(page);
while( matcher.find() )
{
int begin = matcher.start();
int end = matcher.end();
highlighterOutput.write(" <loc " +
"pg=" + (getCurrentPageNo()-1)
+ " pos=" + begin
+ " len="+ (end - begin)
+ ">\n");
}
}
}
/**
* Command line application.
*
* @param args The command line arguments to the application.
*
* @throws IOException If there is an error generating the highlight file.
*/
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static void usage()
{
System.err.println( "usage: java " + PDFHighlighter.class.getName() + " <pdf file> word1 word2 word3 ..." );
System.exit( 1 );
}
}
|
PDFHighlighter xmlExtractor = new PDFHighlighter();
if (args.length < 2)
{
usage();
}
String[] highlightStrings = new String[args.length - 1];
System.arraycopy(args, 1, highlightStrings, 0, highlightStrings.length);
try (PDDocument doc = Loader.loadPDF(new File(args[0])))
{
xmlExtractor.generateXMLHighlight(
doc,
highlightStrings,
new OutputStreamWriter( System.out ) );
}
| 1,012
| 144
| 1,156
|
<methods>public void <init>() ,public boolean getAddMoreFormatting() ,public java.lang.String getArticleEnd() ,public java.lang.String getArticleStart() ,public float getAverageCharTolerance() ,public float getDropThreshold() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getEndBookmark() ,public int getEndPage() ,public float getIndentThreshold() ,public java.lang.String getLineSeparator() ,public java.lang.String getPageEnd() ,public java.lang.String getPageStart() ,public java.lang.String getParagraphEnd() ,public java.lang.String getParagraphStart() ,public boolean getSeparateByBeads() ,public boolean getSortByPosition() ,public float getSpacingTolerance() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getStartBookmark() ,public int getStartPage() ,public boolean getSuppressDuplicateOverlappingText() ,public java.lang.String getText(org.apache.pdfbox.pdmodel.PDDocument) throws java.io.IOException,public java.lang.String getWordSeparator() ,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void setAddMoreFormatting(boolean) ,public void setArticleEnd(java.lang.String) ,public void setArticleStart(java.lang.String) ,public void setAverageCharTolerance(float) ,public void setDropThreshold(float) ,public void setEndBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setEndPage(int) ,public void setIndentThreshold(float) ,public void setLineSeparator(java.lang.String) ,public void setPageEnd(java.lang.String) ,public void setPageStart(java.lang.String) ,public void setParagraphEnd(java.lang.String) ,public void setParagraphStart(java.lang.String) ,public void setShouldSeparateByBeads(boolean) ,public void setSortByPosition(boolean) ,public void setSpacingTolerance(float) ,public void setStartBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setStartPage(int) ,public void setSuppressDuplicateOverlappingText(boolean) ,public void setWordSeparator(java.lang.String) ,public void writeText(org.apache.pdfbox.pdmodel.PDDocument, java.io.Writer) throws java.io.IOException<variables>private static final float END_OF_LAST_TEXT_X_RESET_VALUE,private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE,private static final float LAST_WORD_SPACING_RESET_VALUE,protected static final java.lang.String LINE_SEPARATOR,private static final java.lang.String[] LIST_ITEM_EXPRESSIONS,private static final Logger LOG,private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE,private static final float MAX_Y_FOR_LINE_RESET_VALUE,private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE,private static final Map<java.lang.Character,java.lang.Character> MIRRORING_CHAR_MAP,private boolean addMoreFormatting,private java.lang.String articleEnd,private java.lang.String articleStart,private float averageCharTolerance,private List<org.apache.pdfbox.pdmodel.common.PDRectangle> beadRectangles,private final Map<java.lang.String,TreeMap<java.lang.Float,TreeSet<java.lang.Float>>> characterListMapping,protected ArrayList<List<org.apache.pdfbox.text.TextPosition>> charactersByArticle,private int currentPageNo,private static float defaultDropThreshold,private static float defaultIndentThreshold,protected org.apache.pdfbox.pdmodel.PDDocument document,private float dropThreshold,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem endBookmark,private int endBookmarkPageNumber,private int endPage,private boolean inParagraph,private float indentThreshold,private java.lang.String lineSeparator,private List<java.util.regex.Pattern> listOfPatterns,protected java.io.Writer output,private java.lang.String pageEnd,private java.lang.String pageStart,private java.lang.String paragraphEnd,private java.lang.String paragraphStart,private boolean shouldSeparateByBeads,private boolean sortByPosition,private float spacingTolerance,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem startBookmark,private int startBookmarkPageNumber,private int startPage,private boolean suppressDuplicateOverlappingText,private java.lang.String wordSeparator
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/PDFMergerExample.java
|
PDFMergerExample
|
createXMPMetadata
|
class PDFMergerExample
{
private static final Logger LOG = LogManager.getLogger(PDFMergerExample.class);
/**
* Creates a compound PDF document from a list of input documents.
* <p>
* The merged document is PDF/A-1b compliant, provided the source documents are as well. It contains document
* properties title, creator and subject, currently hard-coded.
*
* @param sources list of source PDF documents as RandomAccessRead.
* @return compound PDF document as a readable input stream.
* @throws IOException if anything goes wrong during PDF merge.
*/
public InputStream merge(final List<RandomAccessRead> sources) throws IOException
{
String title = "My title";
String creator = "Alexander Kriegisch";
String subject = "Subject with umlauts ÄÖÜ";
try (COSStream cosStream = new COSStream();
ByteArrayOutputStream mergedPDFOutputStream = new ByteArrayOutputStream())
{
// If you're merging in a servlet, you can modify this example to use the outputStream only
// as the response as shown here: http://stackoverflow.com/a/36894346/535646
PDFMergerUtility pdfMerger = createPDFMergerUtility(sources, mergedPDFOutputStream);
// PDF and XMP properties must be identical, otherwise document is not PDF/A compliant
PDDocumentInformation pdfDocumentInfo = createPDFDocumentInfo(title, creator, subject);
PDMetadata xmpMetadata = createXMPMetadata(cosStream, title, creator, subject);
pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo);
pdfMerger.setDestinationMetadata(xmpMetadata);
LOG.info("Merging {} source documents into one PDF", sources.size());
pdfMerger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache());
LOG.info("PDF merge successful, size = {{}} bytes", mergedPDFOutputStream.size());
return new ByteArrayInputStream(mergedPDFOutputStream.toByteArray());
}
catch (BadFieldValueException | TransformerException e)
{
throw new IOException("PDF merge problem", e);
}
finally
{
sources.forEach(IOUtils::closeQuietly);
}
}
private PDFMergerUtility createPDFMergerUtility(List<RandomAccessRead> sources,
ByteArrayOutputStream mergedPDFOutputStream)
{
LOG.info("Initialising PDF merge utility");
PDFMergerUtility pdfMerger = new PDFMergerUtility();
pdfMerger.addSources(sources);
pdfMerger.setDestinationStream(mergedPDFOutputStream);
return pdfMerger;
}
private PDDocumentInformation createPDFDocumentInfo(String title, String creator, String subject)
{
LOG.info("Setting document info (title, author, subject) for merged PDF");
PDDocumentInformation documentInformation = new PDDocumentInformation();
documentInformation.setTitle(title);
documentInformation.setCreator(creator);
documentInformation.setSubject(subject);
return documentInformation;
}
private PDMetadata createXMPMetadata(COSStream cosStream, String title, String creator, String subject)
throws BadFieldValueException, TransformerException, IOException
{<FILL_FUNCTION_BODY>}
}
|
LOG.info("Setting XMP metadata (title, author, subject) for merged PDF");
XMPMetadata xmpMetadata = XMPMetadata.createXMPMetadata();
// PDF/A-1b properties
PDFAIdentificationSchema pdfaSchema = xmpMetadata.createAndAddPDFAIdentificationSchema();
pdfaSchema.setPart(1);
pdfaSchema.setConformance("B");
// Dublin Core properties
DublinCoreSchema dublinCoreSchema = xmpMetadata.createAndAddDublinCoreSchema();
dublinCoreSchema.setTitle(title);
dublinCoreSchema.addCreator(creator);
dublinCoreSchema.setDescription(subject);
// XMP Basic properties
XMPBasicSchema basicSchema = xmpMetadata.createAndAddXMPBasicSchema();
Calendar creationDate = Calendar.getInstance();
basicSchema.setCreateDate(creationDate);
basicSchema.setModifyDate(creationDate);
basicSchema.setMetadataDate(creationDate);
basicSchema.setCreatorTool(creator);
// Create and return XMP data structure in XML format
try (ByteArrayOutputStream xmpOutputStream = new ByteArrayOutputStream();
OutputStream cosXMPStream = cosStream.createOutputStream())
{
new XmpSerializer().serialize(xmpMetadata, xmpOutputStream, true);
cosXMPStream.write(xmpOutputStream.toByteArray());
return new PDMetadata(cosStream);
}
| 855
| 360
| 1,215
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/PrintImageLocations.java
|
PrintImageLocations
|
main
|
class PrintImageLocations extends PDFStreamEngine
{
/**
* Default constructor.
*
* @throws IOException If there is an error loading text stripper properties.
*/
public PrintImageLocations() throws IOException
{
addOperator(new Concatenate(this));
addOperator(new DrawObject(this));
addOperator(new SetGraphicsStateParameters(this));
addOperator(new Save(this));
addOperator(new Restore(this));
addOperator(new SetMatrix(this));
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This is used to handle an operation.
*
* @param operator The operation to perform.
* @param operands The list of arguments.
*
* @throws IOException If there is an error processing the operation.
*/
@Override
protected void processOperator( Operator operator, List<COSBase> operands) throws IOException
{
String operation = operator.getName();
if (OperatorName.DRAW_OBJECT.equals(operation))
{
COSName objectName = (COSName) operands.get( 0 );
PDXObject xobject = getResources().getXObject( objectName );
if( xobject instanceof PDImageXObject)
{
PDImageXObject image = (PDImageXObject)xobject;
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
System.out.println("*******************************************************************");
System.out.println("Found image [" + objectName.getName() + "]");
Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
float imageXScale = ctmNew.getScalingFactorX();
float imageYScale = ctmNew.getScalingFactorY();
// position in user space units. 1 unit = 1/72 inch at 72 dpi
System.out.println("position in PDF = " + ctmNew.getTranslateX() + ", " + ctmNew.getTranslateY() + " in user space units");
// raw size in pixels
System.out.println("raw image size = " + imageWidth + ", " + imageHeight + " in pixels");
// displayed size in user space units
System.out.println("displayed size = " + imageXScale + ", " + imageYScale + " in user space units");
// displayed size in inches at 72 dpi rendering
imageXScale /= 72;
imageYScale /= 72;
System.out.println("displayed size = " + imageXScale + ", " + imageYScale + " in inches at 72 dpi rendering");
// displayed size in millimeters at 72 dpi rendering
imageXScale *= 25.4f;
imageYScale *= 25.4f;
System.out.println("displayed size = " + imageXScale + ", " + imageYScale + " in millimeters at 72 dpi rendering");
System.out.println();
}
else if(xobject instanceof PDFormXObject)
{
PDFormXObject form = (PDFormXObject)xobject;
showForm(form);
}
}
else
{
super.processOperator( operator, operands);
}
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + PrintImageLocations.class.getName() + " <input-pdf>" );
}
}
|
if( args.length != 1 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PrintImageLocations printer = new PrintImageLocations();
int pageNum = 0;
for( PDPage page : document.getPages() )
{
pageNum++;
System.out.println( "Processing page: " + pageNum );
printer.processPage(page);
}
}
}
| 953
| 138
| 1,091
|
<methods>public final void addOperator(org.apache.pdfbox.contentstream.operator.OperatorProcessor) ,public void beginMarkedContentSequence(org.apache.pdfbox.cos.COSName, org.apache.pdfbox.cos.COSDictionary) ,public void beginText() throws java.io.IOException,public void decreaseLevel() ,public void endMarkedContentSequence() ,public void endText() throws java.io.IOException,public org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream getAppearance(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) ,public org.apache.pdfbox.pdmodel.PDPage getCurrentPage() ,public int getGraphicsStackSize() ,public org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState getGraphicsState() ,public org.apache.pdfbox.util.Matrix getInitialMatrix() ,public int getLevel() ,public org.apache.pdfbox.pdmodel.PDResources getResources() ,public org.apache.pdfbox.util.Matrix getTextLineMatrix() ,public org.apache.pdfbox.util.Matrix getTextMatrix() ,public void increaseLevel() ,public void processOperator(java.lang.String, List<org.apache.pdfbox.cos.COSBase>) throws java.io.IOException,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void restoreGraphicsState() ,public void saveGraphicsState() ,public void setLineDashPattern(org.apache.pdfbox.cos.COSArray, int) ,public void setTextLineMatrix(org.apache.pdfbox.util.Matrix) ,public void setTextMatrix(org.apache.pdfbox.util.Matrix) ,public void showAnnotation(org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation) throws java.io.IOException,public void showForm(org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject) throws java.io.IOException,public void showTextString(byte[]) throws java.io.IOException,public void showTextStrings(org.apache.pdfbox.cos.COSArray) throws java.io.IOException,public void showTransparencyGroup(org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup) throws java.io.IOException,public java.awt.geom.Point2D.Float transformedPoint(float, float) <variables>private static final Logger LOG,private org.apache.pdfbox.pdmodel.PDPage currentPage,private org.apache.pdfbox.pdmodel.font.PDFont defaultFont,private Deque<org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState> graphicsStack,private org.apache.pdfbox.util.Matrix initialMatrix,private boolean isProcessingPage,private int level,private final Map<java.lang.String,org.apache.pdfbox.contentstream.operator.OperatorProcessor> operators,private org.apache.pdfbox.pdmodel.PDResources resources
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/PrintTextColors.java
|
PrintTextColors
|
processTextPosition
|
class PrintTextColors extends PDFTextStripper
{
/**
* Instantiate a new PDFTextStripper object.
*
* @throws IOException If there is an error loading the properties.
*/
public PrintTextColors() throws IOException
{
addOperator(new SetStrokingColorSpace(this));
addOperator(new SetNonStrokingColorSpace(this));
addOperator(new SetStrokingDeviceCMYKColor(this));
addOperator(new SetNonStrokingDeviceCMYKColor(this));
addOperator(new SetNonStrokingDeviceRGBColor(this));
addOperator(new SetStrokingDeviceRGBColor(this));
addOperator(new SetNonStrokingDeviceGrayColor(this));
addOperator(new SetStrokingDeviceGrayColor(this));
addOperator(new SetStrokingColor(this));
addOperator(new SetStrokingColorN(this));
addOperator(new SetNonStrokingColor(this));
addOperator(new SetNonStrokingColorN(this));
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main(String[] args) throws IOException
{
if (args.length != 1)
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PDFTextStripper stripper = new PrintTextColors();
stripper.setSortByPosition(true);
stripper.setStartPage(0);
stripper.setEndPage(document.getNumberOfPages());
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
}
}
}
@Override
protected void processTextPosition(TextPosition text)
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println("Usage: java " + PrintTextColors.class.getName() + " <input-pdf>");
}
}
|
super.processTextPosition(text);
PDColor strokingColor = getGraphicsState().getStrokingColor();
PDColor nonStrokingColor = getGraphicsState().getNonStrokingColor();
String unicode = text.getUnicode();
RenderingMode renderingMode = getGraphicsState().getTextState().getRenderingMode();
System.out.println("Unicode: " + unicode);
System.out.println("Rendering mode: " + renderingMode);
System.out.println("Stroking color: " + strokingColor);
System.out.println("Non-Stroking color: " + nonStrokingColor);
System.out.println("Non-Stroking color: " + nonStrokingColor);
System.out.println();
// See the PrintTextLocations for more attributes
| 577
| 210
| 787
|
<methods>public void <init>() ,public boolean getAddMoreFormatting() ,public java.lang.String getArticleEnd() ,public java.lang.String getArticleStart() ,public float getAverageCharTolerance() ,public float getDropThreshold() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getEndBookmark() ,public int getEndPage() ,public float getIndentThreshold() ,public java.lang.String getLineSeparator() ,public java.lang.String getPageEnd() ,public java.lang.String getPageStart() ,public java.lang.String getParagraphEnd() ,public java.lang.String getParagraphStart() ,public boolean getSeparateByBeads() ,public boolean getSortByPosition() ,public float getSpacingTolerance() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getStartBookmark() ,public int getStartPage() ,public boolean getSuppressDuplicateOverlappingText() ,public java.lang.String getText(org.apache.pdfbox.pdmodel.PDDocument) throws java.io.IOException,public java.lang.String getWordSeparator() ,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void setAddMoreFormatting(boolean) ,public void setArticleEnd(java.lang.String) ,public void setArticleStart(java.lang.String) ,public void setAverageCharTolerance(float) ,public void setDropThreshold(float) ,public void setEndBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setEndPage(int) ,public void setIndentThreshold(float) ,public void setLineSeparator(java.lang.String) ,public void setPageEnd(java.lang.String) ,public void setPageStart(java.lang.String) ,public void setParagraphEnd(java.lang.String) ,public void setParagraphStart(java.lang.String) ,public void setShouldSeparateByBeads(boolean) ,public void setSortByPosition(boolean) ,public void setSpacingTolerance(float) ,public void setStartBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setStartPage(int) ,public void setSuppressDuplicateOverlappingText(boolean) ,public void setWordSeparator(java.lang.String) ,public void writeText(org.apache.pdfbox.pdmodel.PDDocument, java.io.Writer) throws java.io.IOException<variables>private static final float END_OF_LAST_TEXT_X_RESET_VALUE,private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE,private static final float LAST_WORD_SPACING_RESET_VALUE,protected static final java.lang.String LINE_SEPARATOR,private static final java.lang.String[] LIST_ITEM_EXPRESSIONS,private static final Logger LOG,private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE,private static final float MAX_Y_FOR_LINE_RESET_VALUE,private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE,private static final Map<java.lang.Character,java.lang.Character> MIRRORING_CHAR_MAP,private boolean addMoreFormatting,private java.lang.String articleEnd,private java.lang.String articleStart,private float averageCharTolerance,private List<org.apache.pdfbox.pdmodel.common.PDRectangle> beadRectangles,private final Map<java.lang.String,TreeMap<java.lang.Float,TreeSet<java.lang.Float>>> characterListMapping,protected ArrayList<List<org.apache.pdfbox.text.TextPosition>> charactersByArticle,private int currentPageNo,private static float defaultDropThreshold,private static float defaultIndentThreshold,protected org.apache.pdfbox.pdmodel.PDDocument document,private float dropThreshold,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem endBookmark,private int endBookmarkPageNumber,private int endPage,private boolean inParagraph,private float indentThreshold,private java.lang.String lineSeparator,private List<java.util.regex.Pattern> listOfPatterns,protected java.io.Writer output,private java.lang.String pageEnd,private java.lang.String pageStart,private java.lang.String paragraphEnd,private java.lang.String paragraphStart,private boolean shouldSeparateByBeads,private boolean sortByPosition,private float spacingTolerance,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem startBookmark,private int startBookmarkPageNumber,private int startPage,private boolean suppressDuplicateOverlappingText,private java.lang.String wordSeparator
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/PrintTextLocations.java
|
PrintTextLocations
|
writeString
|
class PrintTextLocations extends PDFTextStripper
{
/**
* Instantiate a new PDFTextStripper object.
*
* @throws IOException If there is an error loading the properties.
*/
public PrintTextLocations() throws IOException
{
}
/**
* This will print the documents data.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main( String[] args ) throws IOException
{
if( args.length != 1 )
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
PDFTextStripper stripper = new PrintTextLocations();
stripper.setSortByPosition( true );
stripper.setStartPage( 0 );
stripper.setEndPage( document.getNumberOfPages() );
Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
stripper.writeText(document, dummy);
}
}
}
/**
* Override the default functionality of PDFTextStripper.
*/
@Override
protected void writeString(String string, List<TextPosition> textPositions) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println( "Usage: java " + PrintTextLocations.class.getName() + " <input-pdf>" );
}
}
|
for (TextPosition text : textPositions)
{
System.out.println( "String[" + text.getXDirAdj() + "," +
text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale=" +
text.getXScale() + " height=" + text.getHeightDir() + " space=" +
text.getWidthOfSpace() + " width=" +
text.getWidthDirAdj() + "]" + text.getUnicode() );
}
| 414
| 136
| 550
|
<methods>public void <init>() ,public boolean getAddMoreFormatting() ,public java.lang.String getArticleEnd() ,public java.lang.String getArticleStart() ,public float getAverageCharTolerance() ,public float getDropThreshold() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getEndBookmark() ,public int getEndPage() ,public float getIndentThreshold() ,public java.lang.String getLineSeparator() ,public java.lang.String getPageEnd() ,public java.lang.String getPageStart() ,public java.lang.String getParagraphEnd() ,public java.lang.String getParagraphStart() ,public boolean getSeparateByBeads() ,public boolean getSortByPosition() ,public float getSpacingTolerance() ,public org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem getStartBookmark() ,public int getStartPage() ,public boolean getSuppressDuplicateOverlappingText() ,public java.lang.String getText(org.apache.pdfbox.pdmodel.PDDocument) throws java.io.IOException,public java.lang.String getWordSeparator() ,public void processPage(org.apache.pdfbox.pdmodel.PDPage) throws java.io.IOException,public void setAddMoreFormatting(boolean) ,public void setArticleEnd(java.lang.String) ,public void setArticleStart(java.lang.String) ,public void setAverageCharTolerance(float) ,public void setDropThreshold(float) ,public void setEndBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setEndPage(int) ,public void setIndentThreshold(float) ,public void setLineSeparator(java.lang.String) ,public void setPageEnd(java.lang.String) ,public void setPageStart(java.lang.String) ,public void setParagraphEnd(java.lang.String) ,public void setParagraphStart(java.lang.String) ,public void setShouldSeparateByBeads(boolean) ,public void setSortByPosition(boolean) ,public void setSpacingTolerance(float) ,public void setStartBookmark(org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem) ,public void setStartPage(int) ,public void setSuppressDuplicateOverlappingText(boolean) ,public void setWordSeparator(java.lang.String) ,public void writeText(org.apache.pdfbox.pdmodel.PDDocument, java.io.Writer) throws java.io.IOException<variables>private static final float END_OF_LAST_TEXT_X_RESET_VALUE,private static final float EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE,private static final float LAST_WORD_SPACING_RESET_VALUE,protected static final java.lang.String LINE_SEPARATOR,private static final java.lang.String[] LIST_ITEM_EXPRESSIONS,private static final Logger LOG,private static final float MAX_HEIGHT_FOR_LINE_RESET_VALUE,private static final float MAX_Y_FOR_LINE_RESET_VALUE,private static final float MIN_Y_TOP_FOR_LINE_RESET_VALUE,private static final Map<java.lang.Character,java.lang.Character> MIRRORING_CHAR_MAP,private boolean addMoreFormatting,private java.lang.String articleEnd,private java.lang.String articleStart,private float averageCharTolerance,private List<org.apache.pdfbox.pdmodel.common.PDRectangle> beadRectangles,private final Map<java.lang.String,TreeMap<java.lang.Float,TreeSet<java.lang.Float>>> characterListMapping,protected ArrayList<List<org.apache.pdfbox.text.TextPosition>> charactersByArticle,private int currentPageNo,private static float defaultDropThreshold,private static float defaultIndentThreshold,protected org.apache.pdfbox.pdmodel.PDDocument document,private float dropThreshold,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem endBookmark,private int endBookmarkPageNumber,private int endPage,private boolean inParagraph,private float indentThreshold,private java.lang.String lineSeparator,private List<java.util.regex.Pattern> listOfPatterns,protected java.io.Writer output,private java.lang.String pageEnd,private java.lang.String pageStart,private java.lang.String paragraphEnd,private java.lang.String paragraphStart,private boolean shouldSeparateByBeads,private boolean sortByPosition,private float spacingTolerance,private org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem startBookmark,private int startBookmarkPageNumber,private int startPage,private boolean suppressDuplicateOverlappingText,private java.lang.String wordSeparator
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java
|
RemoveAllText
|
main
|
class RemoveAllText
{
/**
* Default constructor.
*/
private RemoveAllText()
{
// example class should not be instantiated
}
/**
* This will remove all text from a PDF document.
*
* @param args The command line arguments.
*
* @throws IOException If there is an error parsing the document.
*/
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static void processResources(PDResources resources) throws IOException
{
for (COSName name : resources.getXObjectNames())
{
PDXObject xobject = resources.getXObject(name);
if (xobject instanceof PDFormXObject)
{
PDFormXObject formXObject = (PDFormXObject) xobject;
writeTokensToStream(formXObject.getContentStream(),
createTokensWithoutText(formXObject));
processResources(formXObject.getResources());
}
}
for (COSName name : resources.getPatternNames())
{
PDAbstractPattern pattern = resources.getPattern(name);
if (pattern instanceof PDTilingPattern)
{
PDTilingPattern tilingPattern = (PDTilingPattern) pattern;
writeTokensToStream(tilingPattern.getContentStream(),
createTokensWithoutText(tilingPattern));
processResources(tilingPattern.getResources());
}
}
}
private static void writeTokensToStream(PDStream newContents, List<Object> newTokens) throws IOException
{
try (OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE))
{
ContentStreamWriter writer = new ContentStreamWriter(out);
writer.writeTokens(newTokens);
}
}
private static List<Object> createTokensWithoutText(PDContentStream contentStream) throws IOException
{
PDFStreamParser parser = new PDFStreamParser(contentStream);
Object token = parser.parseNextToken();
List<Object> newTokens = new ArrayList<>();
while (token != null)
{
if (token instanceof Operator)
{
Operator op = (Operator) token;
String opName = op.getName();
if (OperatorName.SHOW_TEXT_ADJUSTED.equals(opName)
|| OperatorName.SHOW_TEXT.equals(opName)
|| OperatorName.SHOW_TEXT_LINE.equals(opName))
{
// remove the argument to this operator
newTokens.remove(newTokens.size() - 1);
token = parser.parseNextToken();
continue;
}
else if (OperatorName.SHOW_TEXT_LINE_AND_SPACE.equals(opName))
{
// remove the 3 arguments to this operator
newTokens.remove(newTokens.size() - 1);
newTokens.remove(newTokens.size() - 1);
newTokens.remove(newTokens.size() - 1);
token = parser.parseNextToken();
continue;
}
}
newTokens.add(token);
token = parser.parseNextToken();
}
return newTokens;
}
/**
* This will print the usage for this document.
*/
private static void usage()
{
System.err.println(
"Usage: java " + RemoveAllText.class.getName() + " <input-pdf> <output-pdf>");
}
}
|
if (args.length != 2)
{
usage();
}
else
{
try (PDDocument document = Loader.loadPDF(new File(args[0])))
{
if (document.isEncrypted())
{
System.err.println(
"Error: Encrypted documents are not supported for this example.");
System.exit(1);
}
for (PDPage page : document.getPages())
{
List<Object> newTokens = createTokensWithoutText(page);
PDStream newContents = new PDStream(document);
writeTokensToStream(newContents, newTokens);
page.setContents(newContents);
processResources(page.getResources());
}
document.save(args[1]);
}
}
| 896
| 206
| 1,102
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/examples/src/main/java/org/apache/pdfbox/examples/util/SplitBooklet.java
|
SplitBooklet
|
main
|
class SplitBooklet
{
/**
* Default constructor.
*/
private SplitBooklet()
{
// example class should not be instantiated
}
public static void main(String[] args) throws IOException
{<FILL_FUNCTION_BODY>}
private static void usage()
{
System.err.println("Usage: java " + SplitBooklet.class.getName() + " <input-pdf> <output-pdf>");
}
}
|
if (args.length < 2)
{
usage();
System.exit(-1);
}
try (PDDocument document = Loader.loadPDF(new File(args[0]));
PDDocument outdoc = new PDDocument())
{
for (PDPage page : document.getPages())
{
PDRectangle cropBoxORIG = page.getCropBox();
// make sure to have new objects
PDRectangle cropBoxLEFT = new PDRectangle(cropBoxORIG.getCOSArray());
PDRectangle cropBoxRIGHT = new PDRectangle(cropBoxORIG.getCOSArray());
if (page.getRotation() == 90 || page.getRotation() == 270)
{
cropBoxLEFT.setUpperRightY(cropBoxORIG.getLowerLeftY() + cropBoxORIG.getHeight() / 2);
cropBoxRIGHT.setLowerLeftY(cropBoxORIG.getLowerLeftY() + cropBoxORIG.getHeight() / 2);
}
else
{
cropBoxLEFT.setUpperRightX(cropBoxORIG.getLowerLeftX() + cropBoxORIG.getWidth() / 2);
cropBoxRIGHT.setLowerLeftX(cropBoxORIG.getLowerLeftX() + cropBoxORIG.getWidth() / 2);
}
if (page.getRotation() == 180 || page.getRotation() == 270)
{
PDPage pageRIGHT = outdoc.importPage(page);
pageRIGHT.setCropBox(cropBoxRIGHT);
PDPage pageLEFT = outdoc.importPage(page);
pageLEFT.setCropBox(cropBoxLEFT);
}
else
{
PDPage pageLEFT = outdoc.importPage(page);
pageLEFT.setCropBox(cropBoxLEFT);
PDPage pageRIGHT = outdoc.importPage(page);
pageRIGHT.setCropBox(cropBoxRIGHT);
}
}
outdoc.save(args[1]);
// closing must be after saving the destination document
}
| 126
| 566
| 692
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/CFFCIDFont.java
|
CFFCIDFont
|
getType2CharString
|
class CFFCIDFont extends CFFFont
{
private String registry;
private String ordering;
private int supplement;
private List<Map<String, Object>> fontDictionaries = Collections.emptyList();
private List<Map<String, Object>> privateDictionaries = Collections.emptyList();
private FDSelect fdSelect;
private final Map<Integer, CIDKeyedType2CharString> charStringCache =
new ConcurrentHashMap<>();
private Type2CharStringParser charStringParser = null;
private final PrivateType1CharStringReader reader = new PrivateType1CharStringReader();
/**
* Returns the registry value.
*
* @return the registry
*/
public String getRegistry()
{
return registry;
}
/**
* Sets the registry value.
*
* @param registry the registry to set
*/
void setRegistry(String registry)
{
this.registry = registry;
}
/**
* Returns the ordering value.
*
* @return the ordering
*/
public String getOrdering()
{
return ordering;
}
/**
* Sets the ordering value.
*
* @param ordering the ordering to set
*/
void setOrdering(String ordering)
{
this.ordering = ordering;
}
/**
* Returns the supplement value.
*
* @return the supplement
*/
public int getSupplement()
{
return supplement;
}
/**
* Sets the supplement value.
*
* @param supplement the supplement to set
*/
void setSupplement(int supplement)
{
this.supplement = supplement;
}
/**
* Returns the font dictionaries.
*
* @return the fontDict
*/
public List<Map<String, Object>> getFontDicts()
{
return fontDictionaries;
}
/**
* Sets the font dictionaries.
*
* @param fontDict the fontDict to set
*/
void setFontDict(List<Map<String, Object>> fontDict)
{
this.fontDictionaries = fontDict;
}
/**
* Returns the private dictionary.
*
* @return the privDict
*/
public List<Map<String, Object>> getPrivDicts()
{
return privateDictionaries;
}
/**
* Sets the private dictionary.
*
* @param privDict the privDict to set
*/
void setPrivDict(List<Map<String, Object>> privDict)
{
this.privateDictionaries = privDict;
}
/**
* Returns the fdSelect value.
*
* @return the fdSelect
*/
public FDSelect getFdSelect()
{
return fdSelect;
}
/**
* Sets the fdSelect value.
*
* @param fdSelect the fdSelect to set
*/
void setFdSelect(FDSelect fdSelect)
{
this.fdSelect = fdSelect;
}
/**
* Returns the defaultWidthX for the given GID.
*
* @param gid GID
*/
private int getDefaultWidthX(int gid)
{
int fdArrayIndex = this.fdSelect.getFDIndex(gid);
if (fdArrayIndex == -1 || fdArrayIndex >= this.privateDictionaries.size())
{
return 1000;
}
Map<String, Object> privDict = this.privateDictionaries.get(fdArrayIndex);
return privDict.containsKey("defaultWidthX") ? ((Number)privDict.get("defaultWidthX")).intValue() : 1000;
}
/**
* Returns the nominalWidthX for the given GID.
*
* @param gid GID
*/
private int getNominalWidthX(int gid)
{
int fdArrayIndex = this.fdSelect.getFDIndex(gid);
if (fdArrayIndex == -1 || fdArrayIndex >= this.privateDictionaries.size())
{
return 0;
}
Map<String, Object> privDict = this.privateDictionaries.get(fdArrayIndex);
return privDict.containsKey("nominalWidthX") ? ((Number)privDict.get("nominalWidthX")).intValue() : 0;
}
/**
* Returns the LocalSubrIndex for the given GID.
*
* @param gid GID
*/
private byte[][] getLocalSubrIndex(int gid)
{
int fdArrayIndex = this.fdSelect.getFDIndex(gid);
if (fdArrayIndex == -1 || fdArrayIndex >= this.privateDictionaries.size())
{
return null;
}
Map<String, Object> privDict = this.privateDictionaries.get(fdArrayIndex);
return (byte[][])privDict.get("Subrs");
}
/**
* Returns the Type 2 charstring for the given CID.
*
* @param cid CID
* @throws IOException if the charstring could not be read
*/
@Override
public CIDKeyedType2CharString getType2CharString(int cid) throws IOException
{<FILL_FUNCTION_BODY>}
private Type2CharStringParser getParser()
{
if (charStringParser == null)
{
charStringParser = new Type2CharStringParser(getName());
}
return charStringParser;
}
@Override
public GeneralPath getPath(String selector) throws IOException
{
int cid = selectorToCID(selector);
return getType2CharString(cid).getPath();
}
@Override
public float getWidth(String selector) throws IOException
{
int cid = selectorToCID(selector);
return getType2CharString(cid).getWidth();
}
@Override
public boolean hasGlyph(String selector) throws IOException
{
int cid = selectorToCID(selector);
return cid != 0;
}
/**
* Parses a CID selector of the form \ddddd.
*/
private int selectorToCID(String selector)
{
if (!selector.startsWith("\\"))
{
throw new IllegalArgumentException("Invalid selector");
}
return Integer.parseInt(selector.substring(1));
}
/**
* Private implementation of Type1CharStringReader, because only CFFType1Font can
* expose this publicly, as CIDFonts only support this for legacy 'seac' commands.
*/
private class PrivateType1CharStringReader implements Type1CharStringReader
{
@Override
public Type1CharString getType1CharString(String name) throws IOException
{
return CFFCIDFont.this.getType2CharString(0); // .notdef
}
}
}
|
CIDKeyedType2CharString type2 = charStringCache.get(cid);
if (type2 == null)
{
int gid = getCharset().getGIDForCID(cid);
byte[] bytes = charStrings[gid];
if (bytes == null)
{
bytes = charStrings[0]; // .notdef
}
List<Object> type2seq = getParser().parse(bytes, globalSubrIndex,
getLocalSubrIndex(gid), String.format(Locale.US, "%04x", cid));
type2 = new CIDKeyedType2CharString(reader, getName(), cid, gid, type2seq,
getDefaultWidthX(gid), getNominalWidthX(gid));
charStringCache.put(cid, type2);
}
return type2;
| 1,822
| 219
| 2,041
|
<methods>public non-sealed void <init>() ,public void addValueToTopDict(java.lang.String, java.lang.Object) ,public final List<byte[]> getCharStringBytes() ,public org.apache.fontbox.cff.CFFCharset getCharset() ,public byte[] getData() throws java.io.IOException,public org.apache.fontbox.util.BoundingBox getFontBBox() throws java.io.IOException,public List<java.lang.Number> getFontMatrix() ,public List<byte[]> getGlobalSubrIndex() ,public java.lang.String getName() ,public int getNumCharStrings() ,public Map<java.lang.String,java.lang.Object> getTopDict() ,public abstract org.apache.fontbox.cff.Type2CharString getType2CharString(int) throws java.io.IOException,public java.lang.String toString() <variables>protected byte[][] charStrings,private org.apache.fontbox.cff.CFFCharset charset,private java.lang.String fontName,protected byte[][] globalSubrIndex,private org.apache.fontbox.cff.CFFParser.ByteSource source,protected final Map<java.lang.String,java.lang.Object> topDict
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/CFFCharsetCID.java
|
CFFCharsetCID
|
getGIDForCID
|
class CFFCharsetCID implements CFFCharset
{
private static final String EXCEPTION_MESSAGE = "Not a Type 1-equivalent font";
private final Map<Integer, Integer> sidOrCidToGid = new HashMap<>(250);
// inverse
private final Map<Integer, Integer> gidToCid = new HashMap<>();
@Override
public boolean isCIDFont()
{
return true;
}
@Override
public void addSID(int gid, int sid, String name)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public void addCID(int gid, int cid)
{
sidOrCidToGid.put(cid, gid);
gidToCid.put(gid, cid);
}
@Override
public int getSIDForGID(int sid)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public int getGIDForSID(int sid)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public int getGIDForCID(int cid)
{<FILL_FUNCTION_BODY>}
@Override
public int getSID(String name)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public String getNameForGID(int gid)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public int getCIDForGID(int gid)
{
Integer cid = gidToCid.get(gid);
if (cid != null)
{
return cid;
}
return 0;
}
}
|
Integer gid = sidOrCidToGid.get(cid);
if (gid == null)
{
return 0;
}
return gid;
| 499
| 49
| 548
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/CFFCharsetType1.java
|
CFFCharsetType1
|
getGIDForSID
|
class CFFCharsetType1 implements CFFCharset
{
private static final String EXCEPTION_MESSAGE = "Not a CIDFont";
private final Map<Integer, Integer> sidOrCidToGid = new HashMap<>(250);
private final Map<Integer, Integer> gidToSid = new HashMap<>(250);
private final Map<String, Integer> nameToSid = new HashMap<>(250);
// inverse
private final Map<Integer, String> gidToName = new HashMap<>(250);
@Override
public boolean isCIDFont()
{
return false;
}
@Override
public void addSID(int gid, int sid, String name)
{
sidOrCidToGid.put(sid, gid);
gidToSid.put(gid, sid);
nameToSid.put(name, sid);
gidToName.put(gid, name);
}
@Override
public void addCID(int gid, int cid)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public int getSIDForGID(int gid)
{
Integer sid = gidToSid.get(gid);
if (sid == null)
{
return 0;
}
return sid;
}
@Override
public int getGIDForSID(int sid)
{<FILL_FUNCTION_BODY>}
@Override
public int getGIDForCID(int cid)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
@Override
public int getSID(String name)
{
Integer sid = nameToSid.get(name);
if (sid == null)
{
return 0;
}
return sid;
}
@Override
public String getNameForGID(int gid)
{
return gidToName.get(gid);
}
@Override
public int getCIDForGID(int gid)
{
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
}
|
Integer gid = sidOrCidToGid.get(sid);
if (gid == null)
{
return 0;
}
return gid;
| 598
| 50
| 648
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/CFFFont.java
|
CFFFont
|
getFontBBox
|
class CFFFont implements FontBoxFont
{
private String fontName;
private CFFCharset charset;
private CFFParser.ByteSource source;
protected final Map<String, Object> topDict = new LinkedHashMap<>();
protected byte[][] charStrings;
protected byte[][] globalSubrIndex;
/**
* The name of the font.
*
* @return the name of the font
*/
@Override
public String getName()
{
return fontName;
}
/**
* Sets the name of the font.
*
* @param name the name of the font
*/
void setName(String name)
{
fontName = name;
}
/**
* Adds the given key/value pair to the top dictionary.
*
* @param name the given key
* @param value the given value
*/
public void addValueToTopDict(String name, Object value)
{
if (value != null)
{
topDict.put(name, value);
}
}
/**
* Returns the top dictionary.
*
* @return the dictionary
*/
public Map<String, Object> getTopDict()
{
return topDict;
}
/**
* Returns the FontMatrix.
*/
@Override
public List<Number> getFontMatrix()
{
return (List<Number>) topDict.get("FontMatrix");
}
/**
* Returns the FontBBox.
*
* @throws IOException if there are less than 4 numbers
*/
@Override
public BoundingBox getFontBBox() throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Returns the CFFCharset of the font.
*
* @return the charset
*/
public CFFCharset getCharset()
{
return charset;
}
/**
* Sets the CFFCharset of the font.
*
* @param charset the given CFFCharset
*/
void setCharset(CFFCharset charset)
{
this.charset = charset;
}
/**
* Returns the character strings dictionary. For expert users only.
*
* @return the character strings dictionary as a list of byte arrays.
*/
public final List<byte[]> getCharStringBytes()
{
return Arrays.asList(charStrings);
}
/**
* Sets a byte source to re-read the CFF data in the future.
*/
final void setData(CFFParser.ByteSource source)
{
this.source = source;
}
/**
* Returns the CFF data.
*
* @return the cff data as byte array
*
* @throws IOException if the data could not be read
*/
public byte[] getData() throws IOException
{
return source.getBytes();
}
/**
* Returns the number of charstrings in the font.
*
* @return the number of charstrings
*/
public int getNumCharStrings()
{
return charStrings.length;
}
/**
* Sets the global subroutine index data.
*
* @param globalSubrIndexValue a list of the global subroutines.
*/
void setGlobalSubrIndex(byte[][] globalSubrIndexValue)
{
globalSubrIndex = globalSubrIndexValue;
}
/**
* Returns the list containing the global subroutines.
*
* @return a list of the global subroutines.
*/
public List<byte[]> getGlobalSubrIndex()
{
return Arrays.asList(globalSubrIndex);
}
/**
* Returns the Type 2 charstring for the given CID.
*
* @param cidOrGid CID for CIFFont, or GID for Type 1 font
*
* @return the Type2 charstring of the given cid/gid
*
* @throws IOException if the charstring could not be read
*/
public abstract Type2CharString getType2CharString(int cidOrGid) throws IOException;
@Override
public String toString()
{
return getClass().getSimpleName() + "[name=" + fontName + ", topDict=" + topDict
+ ", charset=" + charset + ", charStrings=" + Arrays.deepToString(charStrings)
+ "]";
}
}
|
List<Number> numbers = (List<Number>) topDict.get("FontBBox");
if (numbers.size() < 4)
{
throw new IOException("FontBBox must have 4 numbers, but is " + numbers);
}
return new BoundingBox(numbers);
| 1,179
| 77
| 1,256
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/CFFType1Font.java
|
PrivateType1CharStringReader
|
getNominalWidthX
|
class PrivateType1CharStringReader implements Type1CharStringReader
{
@Override
public Type1CharString getType1CharString(String name) throws IOException
{
return CFFType1Font.this.getType1CharString(name);
}
}
@Override
public GeneralPath getPath(String name) throws IOException
{
return getType1CharString(name).getPath();
}
@Override
public float getWidth(String name) throws IOException
{
return getType1CharString(name).getWidth();
}
@Override
public boolean hasGlyph(String name)
{
int sid = getCharset().getSID(name);
int gid = getCharset().getGIDForSID(sid);
return gid != 0;
}
/**
* Returns the Type 1 charstring for the given PostScript glyph name.
*
* @param name PostScript glyph name
* @return Type1 charstring of the given PostScript glyph name
*
* @throws IOException if the charstring could not be read
*/
public Type1CharString getType1CharString(String name) throws IOException
{
// lookup via charset
int gid = nameToGID(name);
// lookup in CharStrings INDEX
return getType2CharString(gid, name);
}
/**
* Returns the GID for the given PostScript glyph name.
*
* @param name a PostScript glyph name.
* @return GID
*/
public int nameToGID(String name)
{
// some fonts have glyphs beyond their encoding, so we look up by charset SID
int sid = getCharset().getSID(name);
return getCharset().getGIDForSID(sid);
}
/**
* Returns the Type 1 charstring for the given GID.
*
* @param gid GID
* @throws IOException if the charstring could not be read
*/
@Override
public Type2CharString getType2CharString(int gid) throws IOException
{
String name = "GID+" + gid; // for debugging only
return getType2CharString(gid, name);
}
// Returns the Type 2 charstring for the given GID, with name for debugging
private Type2CharString getType2CharString(int gid, String name) throws IOException
{
Type2CharString type2 = charStringCache.get(gid);
if (type2 == null)
{
byte[] bytes = null;
if (gid < charStrings.length)
{
bytes = charStrings[gid];
}
if (bytes == null)
{
// .notdef
bytes = charStrings[0];
}
List<Object> type2seq = getParser().parse(bytes, globalSubrIndex, getLocalSubrIndex(),
name);
type2 = new Type2CharString(reader, getName(), name, gid, type2seq, getDefaultWidthX(),
getNominalWidthX());
charStringCache.put(gid, type2);
}
return type2;
}
private Type2CharStringParser getParser()
{
if (charStringParser == null)
{
charStringParser = new Type2CharStringParser(getName());
}
return charStringParser;
}
/**
* Returns the private dictionary.
*
* @return the dictionary
*/
public Map<String, Object> getPrivateDict()
{
return privateDict;
}
/**
* Adds the given key/value pair to the private dictionary.
*
* @param name the given key
* @param value the given value
*/
void addToPrivateDict(String name, Object value)
{
if (value != null)
{
privateDict.put(name, value);
}
}
/**
* Returns the CFFEncoding of the font.
*
* @return the encoding
*/
@Override
public CFFEncoding getEncoding()
{
return encoding;
}
/**
* Sets the CFFEncoding of the font.
*
* @param encoding the given CFFEncoding
*/
void setEncoding(CFFEncoding encoding)
{
this.encoding = encoding;
}
private byte[][] getLocalSubrIndex()
{
if (localSubrIndex == null)
{
localSubrIndex = (byte[][]) privateDict.get("Subrs");
}
return localSubrIndex;
}
// helper for looking up keys/values
private Object getProperty(String name)
{
Object topDictValue = topDict.get(name);
if (topDictValue != null)
{
return topDictValue;
}
return privateDict.get(name);
}
private int getDefaultWidthX()
{
if (defaultWidthX == Integer.MIN_VALUE)
{
Number num = (Number) getProperty("defaultWidthX");
defaultWidthX = num != null ? num.intValue() : 1000;
}
return defaultWidthX;
}
private int getNominalWidthX()
{<FILL_FUNCTION_BODY>
|
if (nominalWidthX == Integer.MIN_VALUE)
{
Number num = (Number) getProperty("nominalWidthX");
nominalWidthX = num != null ? num.intValue() : 0;
}
return nominalWidthX;
| 1,386
| 67
| 1,453
|
<methods>public non-sealed void <init>() ,public void addValueToTopDict(java.lang.String, java.lang.Object) ,public final List<byte[]> getCharStringBytes() ,public org.apache.fontbox.cff.CFFCharset getCharset() ,public byte[] getData() throws java.io.IOException,public org.apache.fontbox.util.BoundingBox getFontBBox() throws java.io.IOException,public List<java.lang.Number> getFontMatrix() ,public List<byte[]> getGlobalSubrIndex() ,public java.lang.String getName() ,public int getNumCharStrings() ,public Map<java.lang.String,java.lang.Object> getTopDict() ,public abstract org.apache.fontbox.cff.Type2CharString getType2CharString(int) throws java.io.IOException,public java.lang.String toString() <variables>protected byte[][] charStrings,private org.apache.fontbox.cff.CFFCharset charset,private java.lang.String fontName,protected byte[][] globalSubrIndex,private org.apache.fontbox.cff.CFFParser.ByteSource source,protected final Map<java.lang.String,java.lang.Object> topDict
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/DataInputByteArray.java
|
DataInputByteArray
|
setPosition
|
class DataInputByteArray implements DataInput
{
private final byte[] inputBuffer;
private int bufferPosition = 0;
/**
* Constructor.
* @param buffer the buffer to be read
*/
public DataInputByteArray(byte[] buffer)
{
inputBuffer = buffer;
}
/**
* Determines if there are any bytes left to read or not.
* @return true if there are any bytes left to read
*/
@Override
public boolean hasRemaining() throws IOException
{
return bufferPosition < inputBuffer.length;
}
/**
* Returns the current position.
* @return current position
*/
@Override
public int getPosition()
{
return bufferPosition;
}
/**
* Sets the current position to the given value.
*
* @param position the given position
* @throws IOException if the new position ist out of range
*/
@Override
public void setPosition(int position) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Read one single byte from the buffer.
* @return the byte
* @throws IOException if an error occurs during reading
*/
@Override
public byte readByte() throws IOException
{
if (!hasRemaining())
{
throw new IOException("End off buffer reached");
}
return inputBuffer[bufferPosition++];
}
/**
* Read one single unsigned byte from the buffer.
* @return the unsigned byte as int
* @throws IOException if an error occurs during reading
*/
@Override
public int readUnsignedByte() throws IOException
{
if (!hasRemaining())
{
throw new IOException("End off buffer reached");
}
return inputBuffer[bufferPosition++] & 0xff;
}
/**
* Peeks one single unsigned byte from the buffer.
*
* @param offset offset to the byte to be peeked
* @return the unsigned byte as int
* @throws IOException if an error occurs during reading
*/
@Override
public int peekUnsignedByte(int offset) throws IOException
{
if (offset < 0)
{
throw new IOException("offset is negative");
}
if (bufferPosition + offset >= inputBuffer.length)
{
throw new IOException("Offset position is out of range " + (bufferPosition + offset)
+ " >= " + inputBuffer.length);
}
return inputBuffer[bufferPosition + offset] & 0xff;
}
/**
* Read a number of single byte values from the buffer.
* @param length the number of bytes to be read
* @return an array with containing the bytes from the buffer
* @throws IOException if an error occurs during reading
*/
@Override
public byte[] readBytes(int length) throws IOException
{
if (length < 0)
{
throw new IOException("length is negative");
}
if (inputBuffer.length - bufferPosition < length)
{
throw new IOException("Premature end of buffer reached");
}
byte[] bytes = new byte[length];
System.arraycopy(inputBuffer, bufferPosition, bytes, 0, length);
bufferPosition += length;
return bytes;
}
@Override
public int length() throws IOException
{
return inputBuffer.length;
}
}
|
if (position < 0)
{
throw new IOException("position is negative");
}
if (position >= inputBuffer.length)
{
throw new IOException(
"New position is out of range " + position + " >= " + inputBuffer.length);
}
bufferPosition = position;
| 861
| 79
| 940
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cff/DataInputRandomAccessRead.java
|
DataInputRandomAccessRead
|
peekUnsignedByte
|
class DataInputRandomAccessRead implements DataInput
{
private final RandomAccessRead randomAccessRead;
/**
* Constructor.
*
* @param randomAccessRead the source to be read from
*/
public DataInputRandomAccessRead(RandomAccessRead randomAccessRead)
{
this.randomAccessRead = randomAccessRead;
}
/**
* Determines if there are any bytes left to read or not.
*
* @return true if there are any bytes left to read.
* @throws IOException when the underlying buffer has already been closed.
*/
@Override
public boolean hasRemaining() throws IOException
{
return randomAccessRead.available() > 0;
}
/**
* Returns the current position.
*
* @return current position.
* @throws IOException when the underlying buffer has already been closed.
*/
@Override
public int getPosition() throws IOException
{
return (int) randomAccessRead.getPosition();
}
/**
* Sets the current <i>absolute</i> position to the given value. You <i>cannot</i> use
* <code>setPosition(-20)</code> to move 20 bytes back!
*
* @param position the given position, must be 0 ≤ position < length.
* @throws IOException if the new position is out of range or when the underlying buffer has
* already been closed.
*/
@Override
public void setPosition(int position) throws IOException
{
if (position < 0)
{
throw new IOException("position is negative");
}
if (position >= randomAccessRead.length())
{
throw new IOException("New position is out of range " + position + " >= "
+ randomAccessRead.length());
}
randomAccessRead.seek(position);
}
/**
* Read one single byte from the buffer.
*
* @return the byte.
* @throws IOException when there are no bytes to read or when the underlying buffer has already
* been closed.
*/
@Override
public byte readByte() throws IOException
{
if (!hasRemaining())
{
throw new IOException("End of buffer reached!");
}
return (byte) randomAccessRead.read();
}
/**
* Read one single unsigned byte from the buffer.
*
* @return the unsigned byte as int.
* @throws IOException when there are no bytes to reador when the underlying buffer has been
* already closed.
*/
@Override
public int readUnsignedByte() throws IOException
{
if (!hasRemaining())
{
throw new IOException("End of buffer reached!");
}
return randomAccessRead.read();
}
/**
* Peeks one single unsigned byte from the buffer.
*
* @param offset offset to the byte to be peeked, must be 0 ≤ offset.
* @return the unsigned byte as int.
* @throws IOException when the offset is negative or beyond end_of_buffer, or when the
* underlying buffer has already been closed.
*/
@Override
public int peekUnsignedByte(int offset) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Read a number of single byte values from the buffer.<br>
* Note: when <code>readBytes(5)</code> is called, but there are only 3 bytes available, the
* caller gets an IOException, not the 3 bytes!
*
* @param length the number of bytes to be read, must be 0 ≤ length.
* @return an array with containing the bytes from the buffer.
* @throws IOException when there are less than <code>length</code> bytes available or when the
* underlying buffer has already been closed.
*/
@Override
public byte[] readBytes(int length) throws IOException
{
if (length < 0)
{
throw new IOException("length is negative");
}
if (randomAccessRead.length() - randomAccessRead.getPosition() < length)
{
throw new IOException("Premature end of buffer reached");
}
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
{
bytes[i] = readByte();
}
return bytes;
}
@Override
public int length() throws IOException
{
return (int) randomAccessRead.length();
}
}
|
if (offset < 0)
{
throw new IOException("offset is negative");
}
if (offset == 0)
{
return randomAccessRead.peek();
}
long currentPosition = randomAccessRead.getPosition();
if (currentPosition + offset >= randomAccessRead.length())
{
throw new IOException("Offset position is out of range " + (currentPosition + offset)
+ " >= " + randomAccessRead.length());
}
randomAccessRead.seek(currentPosition + offset);
int peekValue = randomAccessRead.read();
randomAccessRead.seek(currentPosition);
return peekValue;
| 1,135
| 162
| 1,297
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cmap/CIDRange.java
|
CIDRange
|
extend
|
class CIDRange
{
private final int from;
private int to;
private final int unicode;
private final int codeLength;
/**
* Constructor.
*
* @param from start value of COD range
* @param to end value of CID range
* @param unicode unicode start value
* @param codeLength byte length of CID values
*/
CIDRange(int from, int to, int unicode, int codeLength)
{
this.from = from;
this.to = to;
this.unicode = unicode;
this.codeLength = codeLength;
}
/**
* Returns the byte length of the codes of the CID range.
*
* @return the code length
*/
public int getCodeLength()
{
return codeLength;
}
/**
* Maps the given Unicode character to the corresponding CID in this range.
*
* @param bytes Unicode character
* @return corresponding CID, or -1 if the character is out of range
*/
public int map(byte[] bytes)
{
if (bytes.length == codeLength)
{
int ch = CMap.toInt(bytes);
if (from <= ch && ch <= to)
{
return unicode + (ch - from);
}
}
return -1;
}
/**
* Maps the given Unicode character to the corresponding CID in this range.
*
* @param code Unicode character
* @param length origin byte length of the code
* @return corresponding CID, or -1 if the character is out of range
*/
public int map(int code, int length)
{
if (length == codeLength && from <= code && code <= to)
{
return unicode + (code - from);
}
return -1;
}
/**
* Maps the given CID to the corresponding Unicode character in this range.
*
* @param code CID
* @return corresponding Unicode character, or -1 if the CID is out of range
*/
public int unmap(int code)
{
if (unicode <= code && code <= unicode + (to - from))
{
return from + (code - unicode);
}
return -1;
}
/**
* Check if the given values represent a consecutive range of the given range. If so, extend the given range instead of
* creating a new one.
*
* @param newFrom start value of the new range
* @param newTo end value of the new range
* @param newCid start CID value of the range
* @param length byte length of CIDs
* @return true if the given range was extended
*/
public boolean extend(int newFrom, int newTo, int newCid, int length)
{<FILL_FUNCTION_BODY>}
}
|
if (codeLength == length && (newFrom == to + 1) && (newCid == unicode + to - from + 1))
{
to = newTo;
return true;
}
return false;
| 757
| 58
| 815
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/cmap/CodespaceRange.java
|
CodespaceRange
|
isFullMatch
|
class CodespaceRange
{
private final int[] start;
private final int[] end;
private final int codeLength;
/**
* Creates a new instance of CodespaceRange. The length of both arrays has to be the same.<br>
* For one byte ranges startBytes and endBytes define a linear range of values. Double byte values define a
* rectangular range not a linear range. Examples: <br>
* <00> <20> defines a linear range from 0x00 up to 0x20.<br>
* <8140> to <9FFC> defines a rectangular range. The high byte has to be within 0x81 and 0x9F and the
* low byte has to be within 0x40 and 0xFC
*
* @param startBytes start of the range
* @param endBytes start of the range
*/
public CodespaceRange(byte[] startBytes, byte[] endBytes)
{
byte[] correctedStartBytes = startBytes;
if (startBytes.length != endBytes.length && startBytes.length == 1 && startBytes[0] == 0)
{
correctedStartBytes = new byte[endBytes.length];
}
else if (startBytes.length != endBytes.length)
{
throw new IllegalArgumentException(
"The start and the end values must not have different lengths.");
}
start = new int[correctedStartBytes.length];
end = new int[endBytes.length];
for (int i = 0; i < correctedStartBytes.length; i++)
{
start[i] = correctedStartBytes[i] & 0xFF;
end[i] = endBytes[i] & 0xFF;
}
codeLength = endBytes.length;
}
/**
* Returns the length of the codes of the codespace.
*
* @return the code length
*/
public int getCodeLength()
{
return codeLength;
}
/**
* Returns true if the given code bytes match this codespace range.
*
* @param code the code bytes to be matched
*
* @return true if the given code bytes match this codespace range
*/
public boolean matches(byte[] code)
{
return isFullMatch(code, code.length);
}
/**
* Returns true if the given number of code bytes match this codespace range.
*
* @param code the code bytes to be matched
* @param codeLen the code length to be used for matching
*
* @return true if the given number of code bytes match this codespace range
*/
public boolean isFullMatch(byte[] code, int codeLen)
{<FILL_FUNCTION_BODY>}
}
|
// code must be the same length as the bounding codes
if (codeLength != codeLen)
{
return false;
}
for (int i = 0; i < codeLength; i++)
{
int codeAsInt = code[i] & 0xFF;
if (codeAsInt < start[i] || codeAsInt > end[i])
{
return false;
}
}
return true;
| 720
| 116
| 836
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/encoding/Encoding.java
|
Encoding
|
getName
|
class Encoding
{
/**
* This is a mapping from a character code to a character name.
*/
private final Map<Integer, String> codeToName = new HashMap<>(250);
/**
* This is a mapping from a character name to a character code.
*/
private final Map<String, Integer> nameToCode = new HashMap<>(250);
/**
* This will add a character encoding.
*
* @param code The character code that matches the character.
* @param name The name of the character.
*/
protected void addCharacterEncoding( int code, String name )
{
codeToName.put( code, name );
nameToCode.put( name, code );
}
/**
* This will get the character code for the name.
*
* @param name The name of the character.
* @return The code for the character or null if it is not in the encoding.
*/
public Integer getCode( String name )
{
return nameToCode.get( name );
}
/**
* This will take a character code and get the name from the code. This method will never return
* null.
*
* @param code The character code.
* @return The name of the character, or ".notdef" if the bame doesn't exist.
*/
public String getName( int code )
{<FILL_FUNCTION_BODY>}
/**
* Returns an unmodifiable view of the code to name mapping.
*
* @return the Code2Name map
*/
public Map<Integer, String> getCodeToNameMap()
{
return Collections.unmodifiableMap(codeToName);
}
}
|
String name = codeToName.get( code );
if (name != null)
{
return name;
}
return ".notdef";
| 442
| 43
| 485
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/pfb/PfbParser.java
|
PfbParser
|
parsePfb
|
class PfbParser
{
private static final Logger LOG = LogManager.getLogger(PfbParser.class);
/**
* the pfb header length.
* (start-marker (1 byte), ascii-/binary-marker (1 byte), size (4 byte))
* 3*6 == 18
*/
private static final int PFB_HEADER_LENGTH = 18;
/**
* the start marker.
*/
private static final int START_MARKER = 0x80;
/**
* the ascii marker.
*/
private static final int ASCII_MARKER = 0x01;
/**
* the binary marker.
*/
private static final int BINARY_MARKER = 0x02;
/**
* the EOF marker.
*/
private static final int EOF_MARKER = 0x03;
/**
* the parsed pfb-data.
*/
private byte[] pfbdata;
/**
* the lengths of the records (ASCII, BINARY, ASCII)
*/
private final int[] lengths = new int[3];
// sample (pfb-file)
// 00000000 80 01 8b 15 00 00 25 21 50 53 2d 41 64 6f 62 65
// ......%!PS-Adobe
/**
* Create a new object.
* @param filename the file name
* @throws IOException if an IO-error occurs.
*/
public PfbParser(final String filename) throws IOException
{
this(Files.readAllBytes(Paths.get(filename)));
}
/**
* Create a new object.
* @param in The input.
* @throws IOException if an IO-error occurs.
*/
public PfbParser(final InputStream in) throws IOException
{
byte[] pfb = in.readAllBytes();
parsePfb(pfb);
}
/**
* Create a new object.
* @param bytes The input.
* @throws IOException if an IO-error occurs.
*/
public PfbParser(final byte[] bytes) throws IOException
{
parsePfb(bytes);
}
/**
* Parse the pfb-array.
* @param pfb The pfb-Array
* @throws IOException in an IO-error occurs.
*/
private void parsePfb(final byte[] pfb) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Returns the lengths.
* @return Returns the lengths.
*/
public int[] getLengths()
{
return lengths;
}
/**
* Returns the pfbdata.
* @return Returns the pfbdata.
*/
public byte[] getPfbdata()
{
return pfbdata;
}
/**
* Returns the pfb data as stream.
* @return Returns the pfb data as stream.
*/
public InputStream getInputStream()
{
return new ByteArrayInputStream(pfbdata);
}
/**
* Returns the size of the pfb-data.
* @return Returns the size of the pfb-data.
*/
public int size()
{
return pfbdata.length;
}
/**
* Returns the first segment
* @return first segment bytes
*/
public byte[] getSegment1()
{
return Arrays.copyOfRange(pfbdata, 0, lengths[0]);
}
/**
* Returns the second segment
* @return second segment bytes
*/
public byte[] getSegment2()
{
return Arrays.copyOfRange(pfbdata, lengths[0], lengths[0] + lengths[1]);
}
}
|
if (pfb.length < PFB_HEADER_LENGTH)
{
throw new IOException("PFB header missing");
}
// read into segments and keep them
List<Integer> typeList = new ArrayList<>(3);
List<byte[]> barrList = new ArrayList<>(3);
ByteArrayInputStream in = new ByteArrayInputStream(pfb);
int total = 0;
do
{
int r = in.read();
if (r == -1 && total > 0)
{
break; // EOF
}
if (r != START_MARKER)
{
throw new IOException("Start marker missing");
}
int recordType = in.read();
if (recordType == EOF_MARKER)
{
break;
}
if (recordType != ASCII_MARKER && recordType != BINARY_MARKER)
{
throw new IOException("Incorrect record type: " + recordType);
}
int size = in.read();
size += in.read() << 8;
size += in.read() << 16;
size += in.read() << 24;
LOG.debug("record type: {}, segment size: {}", recordType, size);
byte[] ar = new byte[size];
int got = in.read(ar);
if (got != size)
{
throw new EOFException("EOF while reading PFB font");
}
total += size;
typeList.add(recordType);
barrList.add(ar);
}
while (true);
// We now have ASCII and binary segments. Lets arrange these so that the ASCII segments
// come first, then the binary segments, then the last ASCII segment if it is
// 0000... cleartomark
pfbdata = new byte[total];
byte[] cleartomarkSegment = null;
int dstPos = 0;
// copy the ASCII segments
for (int i = 0; i < typeList.size(); ++i)
{
if (typeList.get(i) != ASCII_MARKER)
{
continue;
}
byte[] ar = barrList.get(i);
if (i == typeList.size() - 1 && ar.length < 600 && new String(ar).contains("cleartomark"))
{
cleartomarkSegment = ar;
continue;
}
System.arraycopy(ar, 0, pfbdata, dstPos, ar.length);
dstPos += ar.length;
}
lengths[0] = dstPos;
// copy the binary segments
for (int i = 0; i < typeList.size(); ++i)
{
if (typeList.get(i) != BINARY_MARKER)
{
continue;
}
byte[] ar = barrList.get(i);
System.arraycopy(ar, 0, pfbdata, dstPos, ar.length);
dstPos += ar.length;
}
lengths[1] = dstPos - lengths[0];
if (cleartomarkSegment != null)
{
System.arraycopy(cleartomarkSegment, 0, pfbdata, dstPos, cleartomarkSegment.length);
lengths[2] = cleartomarkSegment.length;
}
| 1,021
| 872
| 1,893
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/CFFTable.java
|
CFFTable
|
read
|
class CFFTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "CFF ";
private CFFFont cffFont;
CFFTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws java.io.IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Returns the CFF font, which is a compact representation of a PostScript Type 1, or CIDFont
*
* @return the associated CFF font
*/
public CFFFont getFont()
{
return cffFont;
}
/**
* Allows bytes to be re-read later by CFFParser.
*/
private static class CFFBytesource implements CFFParser.ByteSource
{
private final TrueTypeFont ttf;
CFFBytesource(TrueTypeFont ttf)
{
this.ttf = ttf;
}
@Override
public byte[] getBytes() throws IOException
{
return ttf.getTableBytes(ttf.getTableMap().get(CFFTable.TAG));
}
}
}
|
byte[] bytes = data.read((int)getLength());
CFFParser parser = new CFFParser();
cffFont = parser.parse(bytes, new CFFBytesource(ttf)).get(0);
initialized = true;
| 385
| 63
| 448
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/CmapTable.java
|
CmapTable
|
read
|
class CmapTable extends TTFTable
{
/**
* A tag used to identify this table.
*/
public static final String TAG = "cmap";
// platform
public static final int PLATFORM_UNICODE = 0;
public static final int PLATFORM_MACINTOSH = 1;
public static final int PLATFORM_WINDOWS = 3;
// Mac encodings
public static final int ENCODING_MAC_ROMAN = 0;
// Windows encodings
public static final int ENCODING_WIN_SYMBOL = 0; // Unicode, non-standard character set
public static final int ENCODING_WIN_UNICODE_BMP = 1; // Unicode BMP (UCS-2)
public static final int ENCODING_WIN_SHIFT_JIS = 2;
public static final int ENCODING_WIN_BIG5 = 3;
public static final int ENCODING_WIN_PRC = 4;
public static final int ENCODING_WIN_WANSUNG = 5;
public static final int ENCODING_WIN_JOHAB = 6;
public static final int ENCODING_WIN_UNICODE_FULL = 10; // Unicode Full (UCS-4)
// Unicode encodings
public static final int ENCODING_UNICODE_1_0 = 0;
public static final int ENCODING_UNICODE_1_1 = 1;
public static final int ENCODING_UNICODE_2_0_BMP = 3;
public static final int ENCODING_UNICODE_2_0_FULL = 4;
private CmapSubtable[] cmaps;
CmapTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* @return Returns the cmaps.
*/
public CmapSubtable[] getCmaps()
{
return cmaps;
}
/**
* @param cmapsValue The cmaps to set.
*/
public void setCmaps(CmapSubtable[] cmapsValue)
{
cmaps = cmapsValue;
}
/**
* Returns the subtable, if any, for the given platform and encoding.
*
* @param platformId the ID of the given platform
* @param platformEncodingId the ID of the given encoding
*
* @return the subtable, if any, or null
*/
public CmapSubtable getSubtable(int platformId, int platformEncodingId)
{
for (CmapSubtable cmap : cmaps)
{
if (cmap.getPlatformId() == platformId &&
cmap.getPlatformEncodingId() == platformEncodingId)
{
return cmap;
}
}
return null;
}
}
|
@SuppressWarnings({"unused", "squid:S1854", "squid:S1481"})
int version = data.readUnsignedShort();
int numberOfTables = data.readUnsignedShort();
cmaps = new CmapSubtable[numberOfTables];
for (int i = 0; i < numberOfTables; i++)
{
CmapSubtable cmap = new CmapSubtable();
cmap.initData(data);
cmaps[i] = cmap;
}
int numberOfGlyphs = ttf.getNumberOfGlyphs();
for (int i = 0; i < numberOfTables; i++)
{
cmaps[i].initSubtable(this, numberOfGlyphs, data);
}
initialized = true;
| 822
| 214
| 1,036
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/GlyfSimpleDescript.java
|
GlyfSimpleDescript
|
readFlags
|
class GlyfSimpleDescript extends GlyfDescript
{
private int[] endPtsOfContours;
private byte[] flags;
private short[] xCoordinates;
private short[] yCoordinates;
private final int pointCount;
/**
* Constructor for an empty description.
*/
GlyfSimpleDescript()
{
super((short) 0);
pointCount = 0;
}
/**
* Constructor.
*
* @param numberOfContours number of contours
* @param bais the stream to be read
* @param x0 the initial X-position
* @throws IOException is thrown if something went wrong
*/
GlyfSimpleDescript(short numberOfContours, TTFDataStream bais, short x0) throws IOException
{
super(numberOfContours);
/*
* https://developer.apple.com/fonts/TTRefMan/RM06/Chap6glyf.html
* "If a glyph has zero contours, it need not have any glyph data." set the pointCount to zero to initialize
* attributes and avoid nullpointer but maybe there shouldn't have GlyphDescript in the GlyphData?
*/
if (numberOfContours == 0)
{
pointCount = 0;
return;
}
// Simple glyph description
endPtsOfContours = bais.readUnsignedShortArray(numberOfContours);
int lastEndPt = endPtsOfContours[numberOfContours - 1];
if (numberOfContours == 1 && lastEndPt == 65535)
{
// PDFBOX-2939: assume an empty glyph
pointCount = 0;
return;
}
// The last end point index reveals the total number of points
pointCount = lastEndPt + 1;
flags = new byte[pointCount];
xCoordinates = new short[pointCount];
yCoordinates = new short[pointCount];
int instructionCount = bais.readUnsignedShort();
readInstructions(bais, instructionCount);
readFlags(pointCount, bais);
readCoords(pointCount, bais, x0);
}
/**
* {@inheritDoc}
*/
@Override
public int getEndPtOfContours(int i)
{
return endPtsOfContours[i];
}
/**
* {@inheritDoc}
*/
@Override
public byte getFlags(int i)
{
return flags[i];
}
/**
* {@inheritDoc}
*/
@Override
public short getXCoordinate(int i)
{
return xCoordinates[i];
}
/**
* {@inheritDoc}
*/
@Override
public short getYCoordinate(int i)
{
return yCoordinates[i];
}
/**
* {@inheritDoc}
*/
@Override
public boolean isComposite()
{
return false;
}
/**
* {@inheritDoc}
*/
@Override
public int getPointCount()
{
return pointCount;
}
/**
* The table is stored as relative values, but we'll store them as absolutes.
*/
private void readCoords(int count, TTFDataStream bais, short x0) throws IOException
{
short x = x0;
short y = 0;
for (int i = 0; i < count; i++)
{
if ((flags[i] & X_DUAL) != 0)
{
if ((flags[i] & X_SHORT_VECTOR) != 0)
{
x += (short) bais.readUnsignedByte();
}
}
else
{
if ((flags[i] & X_SHORT_VECTOR) != 0)
{
x -= (short) bais.readUnsignedByte();
}
else
{
x += bais.readSignedShort();
}
}
xCoordinates[i] = x;
}
for (int i = 0; i < count; i++)
{
if ((flags[i] & Y_DUAL) != 0)
{
if ((flags[i] & Y_SHORT_VECTOR) != 0)
{
y += (short) bais.readUnsignedByte();
}
}
else
{
if ((flags[i] & Y_SHORT_VECTOR) != 0)
{
y -= (short) bais.readUnsignedByte();
}
else
{
y += bais.readSignedShort();
}
}
yCoordinates[i] = y;
}
}
/**
* The flags are run-length encoded.
*/
private void readFlags(int flagCount, TTFDataStream bais) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
for (int index = 0; index < flagCount; index++)
{
flags[index] = (byte) bais.readUnsignedByte();
if ((flags[index] & REPEAT) != 0)
{
int repeats = bais.readUnsignedByte();
for (int i = 1; i <= repeats; i++)
{
if (index + i >= flags.length)
{
throw new IOException(
"repeat count (" + repeats + ") higher than remaining space");
}
flags[index + i] = flags[index];
}
index += repeats;
}
}
| 1,480
| 185
| 1,665
|
<methods>public int getContourCount() ,public int[] getInstructions() ,public void resolve() <variables>public static final byte ON_CURVE,public static final byte REPEAT,public static final byte X_DUAL,public static final byte X_SHORT_VECTOR,public static final byte Y_DUAL,public static final byte Y_SHORT_VECTOR,private final non-sealed int contourCount,private int[] instructions
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/GlyphData.java
|
GlyphData
|
initData
|
class GlyphData
{
private short xMin;
private short yMin;
private short xMax;
private short yMax;
private BoundingBox boundingBox = null;
private short numberOfContours;
private GlyfDescript glyphDescription = null;
/**
* This will read the required data from the stream.
*
* @param glyphTable The glyph table this glyph belongs to.
* @param data The stream to read the data from.
* @param leftSideBearing The left side bearing for this glyph.
* @throws IOException If there is an error reading the data.
*/
void initData( GlyphTable glyphTable, TTFDataStream data, int leftSideBearing ) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Initialize an empty glyph record.
*/
void initEmptyData()
{
glyphDescription = new GlyfSimpleDescript();
boundingBox = new BoundingBox();
}
/**
* @return Returns the boundingBox.
*/
public BoundingBox getBoundingBox()
{
return boundingBox;
}
/**
* @return Returns the numberOfContours.
*/
public short getNumberOfContours()
{
return numberOfContours;
}
/**
* Returns the description of the glyph.
* @return the glyph description
*/
public GlyphDescription getDescription()
{
return glyphDescription;
}
/**
* Returns the path of the glyph.
* @return the path
*/
public GeneralPath getPath()
{
return new GlyphRenderer(glyphDescription).getPath();
}
/**
* Returns the xMax value.
* @return the XMax value
*/
public short getXMaximum()
{
return xMax;
}
/**
* Returns the xMin value.
* @return the xMin value
*/
public short getXMinimum()
{
return xMin;
}
/**
* Returns the yMax value.
* @return the yMax value
*/
public short getYMaximum()
{
return yMax;
}
/**
* Returns the yMin value.
* @return the yMin value
*/
public short getYMinimum()
{
return yMin;
}
}
|
numberOfContours = data.readSignedShort();
xMin = data.readSignedShort();
yMin = data.readSignedShort();
xMax = data.readSignedShort();
yMax = data.readSignedShort();
boundingBox = new BoundingBox(xMin, yMin, xMax, yMax);
if (numberOfContours >= 0)
{
// create a simple glyph
short x0 = (short) (leftSideBearing - xMin);
glyphDescription = new GlyfSimpleDescript(numberOfContours, data, x0);
}
else
{
// create a composite glyph
glyphDescription = new GlyfCompositeDescript(data, glyphTable);
}
| 636
| 196
| 832
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/GlyphRenderer.java
|
GlyphRenderer
|
describe
|
class GlyphRenderer
{
private static final Logger LOG = LogManager.getLogger(GlyphRenderer.class);
private final GlyphDescription glyphDescription;
GlyphRenderer(GlyphDescription glyphDescription)
{
this.glyphDescription = glyphDescription;
}
/**
* Returns the path of the glyph.
* @return the path
*/
public GeneralPath getPath()
{
Point[] points = describe(glyphDescription);
return calculatePath(points);
}
/**
* Set the points of a glyph from the GlyphDescription.
*/
private Point[] describe(GlyphDescription gd)
{<FILL_FUNCTION_BODY>}
/**
* Use the given points to calculate a GeneralPath.
*
* @param points the points to be used to generate the GeneralPath
*
* @return the calculated GeneralPath
*/
private GeneralPath calculatePath(Point[] points)
{
GeneralPath path = new GeneralPath();
int start = 0;
for (int p = 0, len = points.length; p < len; ++p)
{
if (points[p].endOfContour)
{
Point firstPoint = points[start];
Point lastPoint = points[p];
List<Point> contour = new ArrayList<>();
for (int q = start; q <= p; ++q)
{
contour.add(points[q]);
}
if (points[start].onCurve)
{
// using start point at the contour end
contour.add(firstPoint);
}
else if (points[p].onCurve)
{
// first is off-curve point, trying to use one from the end
contour.add(0, lastPoint);
}
else
{
// start and end are off-curve points, creating implicit one
Point pmid = midValue(firstPoint, lastPoint);
contour.add(0, pmid);
contour.add(pmid);
}
moveTo(path, contour.get(0));
for (int j = 1, clen = contour.size(); j < clen; j++)
{
Point pnow = contour.get(j);
if (pnow.onCurve)
{
lineTo(path, pnow);
}
else if (contour.get(j + 1).onCurve)
{
quadTo(path, pnow, contour.get(j + 1));
++j;
}
else
{
quadTo(path, pnow, midValue(pnow, contour.get(j + 1)));
}
}
path.closePath();
start = p + 1;
}
}
return path;
}
private void moveTo(GeneralPath path, Point point)
{
path.moveTo(point.x, point.y);
LOG.trace("moveTo: {}", () -> String.format(Locale.US, "%d,%d", point.x, point.y));
}
private void lineTo(GeneralPath path, Point point)
{
path.lineTo(point.x, point.y);
LOG.trace("lineTo: {}", () -> String.format(Locale.US, "%d,%d", point.x, point.y));
}
private void quadTo(GeneralPath path, Point ctrlPoint, Point point)
{
path.quadTo(ctrlPoint.x, ctrlPoint.y, point.x, point.y);
LOG.trace("quadTo: {}",
() -> String.format(Locale.US, "%d,%d %d,%d", ctrlPoint.x, ctrlPoint.y, point.x,
point.y));
}
private int midValue(int a, int b)
{
return a + (b - a) / 2;
}
// this creates an onCurve point that is between point1 and point2
private Point midValue(Point point1, Point point2)
{
return new Point(midValue(point1.x, point2.x), midValue(point1.y, point2.y));
}
/**
* This class represents one point of a glyph.
*/
private static class Point
{
private int x = 0;
private int y = 0;
private boolean onCurve = true;
private boolean endOfContour = false;
Point(int xValue, int yValue, boolean onCurveValue, boolean endOfContourValue)
{
x = xValue;
y = yValue;
onCurve = onCurveValue;
endOfContour = endOfContourValue;
}
// this constructs an on-curve, non-endofcountour point
Point(int xValue, int yValue)
{
this(xValue, yValue, true, false);
}
@Override
public String toString()
{
return String.format(Locale.US, "Point(%d,%d,%s,%s)", x, y, onCurve ? "onCurve" : "",
endOfContour ? "endOfContour" : "");
}
}
}
|
int endPtIndex = 0;
int endPtOfContourIndex = -1;
Point[] points = new Point[gd.getPointCount()];
for (int i = 0; i < points.length; i++)
{
if (endPtOfContourIndex == -1)
{
endPtOfContourIndex = gd.getEndPtOfContours(endPtIndex);
}
boolean endPt = endPtOfContourIndex == i;
if (endPt)
{
endPtIndex++;
endPtOfContourIndex = -1;
}
points[i] = new Point(gd.getXCoordinate(i), gd.getYCoordinate(i),
(gd.getFlags(i) & GlyfDescript.ON_CURVE) != 0, endPt);
}
return points;
| 1,506
| 253
| 1,759
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/GlyphTable.java
|
GlyphTable
|
read
|
class GlyphTable extends TTFTable
{
/**
* Tag to identify this table.
*/
public static final String TAG = "glyf";
private GlyphData[] glyphs;
// lazy table reading
private TTFDataStream data;
private IndexToLocationTable loca;
private int numGlyphs;
private int cached = 0;
private HorizontalMetricsTable hmt = null;
/**
* Don't even bother to cache huge fonts.
*/
private static final int MAX_CACHE_SIZE = 5000;
/**
* Don't cache more glyphs than this.
*/
private static final int MAX_CACHED_GLYPHS = 100;
GlyphTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* @param glyphsValue The glyphs to set.
*/
public void setGlyphs(GlyphData[] glyphsValue)
{
glyphs = glyphsValue;
}
/**
* Returns the data for the glyph with the given GID.
*
* @param gid GID
*
* @return data of the glyph with the given GID or null
*
* @throws IOException if the font cannot be read
*/
public GlyphData getGlyph(int gid) throws IOException
{
if (gid < 0 || gid >= numGlyphs)
{
return null;
}
if (glyphs != null && glyphs[gid] != null)
{
return glyphs[gid];
}
GlyphData glyph;
// PDFBOX-4219: synchronize on data because it is accessed by several threads
// when PDFBox is accessing a standard 14 font for the first time
synchronized (data)
{
// read a single glyph
long[] offsets = loca.getOffsets();
if (offsets[gid] == offsets[gid + 1])
{
// no outline
// PDFBOX-5135: can't return null, must return an empty glyph because
// sometimes this is used in a composite glyph.
glyph = new GlyphData();
glyph.initEmptyData();
}
else
{
// save
long currentPosition = data.getCurrentPosition();
data.seek(offsets[gid]);
glyph = getGlyphData(gid);
// restore
data.seek(currentPosition);
}
if (glyphs != null && glyphs[gid] == null && cached < MAX_CACHED_GLYPHS)
{
glyphs[gid] = glyph;
++cached;
}
return glyph;
}
}
private GlyphData getGlyphData(int gid) throws IOException
{
GlyphData glyph = new GlyphData();
int leftSideBearing = hmt == null ? 0 : hmt.getLeftSideBearing(gid);
glyph.initData(this, data, leftSideBearing);
// resolve composite glyph
if (glyph.getDescription().isComposite())
{
glyph.getDescription().resolve();
}
return glyph;
}
}
|
loca = ttf.getIndexToLocation();
numGlyphs = ttf.getNumberOfGlyphs();
if (numGlyphs < MAX_CACHE_SIZE)
{
// don't cache the huge fonts to save memory
glyphs = new GlyphData[numGlyphs];
}
// we don't actually read the complete table here because it can contain tens of thousands of glyphs
// cache the relevant part of the font data so that the data stream can be closed if it is no longer needed
byte[] dataBytes = data.read((int) getLength());
this.data = new RandomAccessReadDataStream(new RandomAccessReadBuffer(dataBytes));
// PDFBOX-5460: read hmtx table early to avoid deadlock if getGlyph() locks "data"
// and then locks TrueTypeFont to read this table, while another thread
// locks TrueTypeFont and then tries to lock "data"
hmt = ttf.getHorizontalMetrics();
initialized = true;
| 962
| 258
| 1,220
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/HorizontalMetricsTable.java
|
HorizontalMetricsTable
|
read
|
class HorizontalMetricsTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "hmtx";
private int[] advanceWidth;
private short[] leftSideBearing;
private short[] nonHorizontalLeftSideBearing;
private int numHMetrics;
HorizontalMetricsTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Returns the advance width for the given GID.
*
* @param gid GID
*
* @return the advance width of the given GID
*/
public int getAdvanceWidth(int gid)
{
if (advanceWidth.length == 0)
{
return 250;
}
if (gid < numHMetrics)
{
return advanceWidth[gid];
}
else
{
// monospaced fonts may not have a width for every glyph
// the last one is for subsequent glyphs
return advanceWidth[advanceWidth.length -1];
}
}
/**
* Returns the left side bearing for the given GID.
*
* @param gid GID
*
* @return the left side bearing of the given GID
*/
public int getLeftSideBearing(int gid)
{
if (leftSideBearing.length == 0)
{
return 0;
}
if (gid < numHMetrics)
{
return leftSideBearing[gid];
}
else
{
return nonHorizontalLeftSideBearing[gid - numHMetrics];
}
}
}
|
HorizontalHeaderTable hHeader = ttf.getHorizontalHeader();
if (hHeader == null)
{
throw new IOException("Could not get hmtx table");
}
numHMetrics = hHeader.getNumberOfHMetrics();
int numGlyphs = ttf.getNumberOfGlyphs();
int bytesRead = 0;
advanceWidth = new int[ numHMetrics ];
leftSideBearing = new short[ numHMetrics ];
for( int i=0; i<numHMetrics; i++ )
{
advanceWidth[i] = data.readUnsignedShort();
leftSideBearing[i] = data.readSignedShort();
bytesRead += 4;
}
int numberNonHorizontal = numGlyphs - numHMetrics;
// handle bad fonts with too many hmetrics
if (numberNonHorizontal < 0)
{
numberNonHorizontal = numGlyphs;
}
// make sure that table is never null and correct size, even with bad fonts that have no
// "leftSideBearing" table, although they should
nonHorizontalLeftSideBearing = new short[numberNonHorizontal];
if (bytesRead < getLength())
{
for( int i=0; i<numberNonHorizontal; i++ )
{
if (bytesRead < getLength())
{
nonHorizontalLeftSideBearing[i] = data.readSignedShort();
bytesRead += 2;
}
}
}
initialized = true;
| 528
| 387
| 915
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/IndexToLocationTable.java
|
IndexToLocationTable
|
read
|
class IndexToLocationTable extends TTFTable
{
private static final short SHORT_OFFSETS = 0;
private static final short LONG_OFFSETS = 1;
/**
* A tag that identifies this table type.
*/
public static final String TAG = "loca";
private long[] offsets;
IndexToLocationTable()
{
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* @return Returns the offsets.
*/
public long[] getOffsets()
{
return offsets;
}
/**
* @param offsetsValue The offsets to set.
*/
public void setOffsets(long[] offsetsValue)
{
offsets = offsetsValue;
}
}
|
HeaderTable head = ttf.getHeader();
if (head == null)
{
throw new IOException("Could not get head table");
}
int numGlyphs = ttf.getNumberOfGlyphs();
offsets = new long[ numGlyphs +1];
for( int i=0; i<numGlyphs+1; i++ )
{
if( head.getIndexToLocFormat() == SHORT_OFFSETS )
{
offsets[i] = data.readUnsignedShort() * 2L;
}
else if( head.getIndexToLocFormat() == LONG_OFFSETS )
{
offsets[i] = data.readUnsignedInt();
}
else
{
throw new IOException( "Error:TTF.loca unknown offset format: " + head.getIndexToLocFormat());
}
}
if (numGlyphs == 1 && offsets[0] == 0 && offsets[1] == 0)
{
// PDFBOX-5794 empty glyph
throw new IOException("The font has no glyphs");
}
initialized = true;
| 289
| 297
| 586
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/KerningTable.java
|
KerningTable
|
read
|
class KerningTable extends TTFTable
{
private static final Logger LOG = LogManager.getLogger(KerningTable.class);
/**
* Tag to identify this table.
*/
public static final String TAG = "kern";
private KerningSubtable[] subtables;
KerningTable()
{
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Obtain first subtable that supports non-cross-stream horizontal kerning.
*
* @return first matching subtable or null if none found
*/
public KerningSubtable getHorizontalKerningSubtable()
{
return getHorizontalKerningSubtable(false);
}
/**
* Obtain first subtable that supports horizontal kerning with specified cross stream.
*
* @param cross true if requesting cross stream horizontal kerning
* @return first matching subtable or null if none found
*/
public KerningSubtable getHorizontalKerningSubtable(boolean cross)
{
if (subtables != null)
{
for (KerningSubtable s : subtables)
{
if (s.isHorizontalKerning(cross))
{
return s;
}
}
}
return null;
}
}
|
int version = data.readUnsignedShort();
if (version != 0)
{
version = (version << 16) | data.readUnsignedShort();
}
int numSubtables = 0;
switch (version)
{
case 0:
numSubtables = data.readUnsignedShort();
break;
case 1:
numSubtables = (int) data.readUnsignedInt();
break;
default:
LOG.debug("Skipped kerning table due to an unsupported kerning table version: {}",
version);
break;
}
if (numSubtables > 0)
{
subtables = new KerningSubtable[numSubtables];
for (int i = 0; i < numSubtables; ++i)
{
KerningSubtable subtable = new KerningSubtable();
subtable.read(data, version);
subtables[i] = subtable;
}
}
initialized = true;
| 415
| 255
| 670
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/MaximumProfileTable.java
|
MaximumProfileTable
|
read
|
class MaximumProfileTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "maxp";
private float version;
private int numGlyphs;
private int maxPoints;
private int maxContours;
private int maxCompositePoints;
private int maxCompositeContours;
private int maxZones;
private int maxTwilightPoints;
private int maxStorage;
private int maxFunctionDefs;
private int maxInstructionDefs;
private int maxStackElements;
private int maxSizeOfInstructions;
private int maxComponentElements;
private int maxComponentDepth;
MaximumProfileTable()
{
super();
}
/**
* @return Returns the maxComponentDepth.
*/
public int getMaxComponentDepth()
{
return maxComponentDepth;
}
/**
* @param maxComponentDepthValue The maxComponentDepth to set.
*/
public void setMaxComponentDepth(int maxComponentDepthValue)
{
this.maxComponentDepth = maxComponentDepthValue;
}
/**
* @return Returns the maxComponentElements.
*/
public int getMaxComponentElements()
{
return maxComponentElements;
}
/**
* @param maxComponentElementsValue The maxComponentElements to set.
*/
public void setMaxComponentElements(int maxComponentElementsValue)
{
this.maxComponentElements = maxComponentElementsValue;
}
/**
* @return Returns the maxCompositeContours.
*/
public int getMaxCompositeContours()
{
return maxCompositeContours;
}
/**
* @param maxCompositeContoursValue The maxCompositeContours to set.
*/
public void setMaxCompositeContours(int maxCompositeContoursValue)
{
this.maxCompositeContours = maxCompositeContoursValue;
}
/**
* @return Returns the maxCompositePoints.
*/
public int getMaxCompositePoints()
{
return maxCompositePoints;
}
/**
* @param maxCompositePointsValue The maxCompositePoints to set.
*/
public void setMaxCompositePoints(int maxCompositePointsValue)
{
this.maxCompositePoints = maxCompositePointsValue;
}
/**
* @return Returns the maxContours.
*/
public int getMaxContours()
{
return maxContours;
}
/**
* @param maxContoursValue The maxContours to set.
*/
public void setMaxContours(int maxContoursValue)
{
this.maxContours = maxContoursValue;
}
/**
* @return Returns the maxFunctionDefs.
*/
public int getMaxFunctionDefs()
{
return maxFunctionDefs;
}
/**
* @param maxFunctionDefsValue The maxFunctionDefs to set.
*/
public void setMaxFunctionDefs(int maxFunctionDefsValue)
{
this.maxFunctionDefs = maxFunctionDefsValue;
}
/**
* @return Returns the maxInstructionDefs.
*/
public int getMaxInstructionDefs()
{
return maxInstructionDefs;
}
/**
* @param maxInstructionDefsValue The maxInstructionDefs to set.
*/
public void setMaxInstructionDefs(int maxInstructionDefsValue)
{
this.maxInstructionDefs = maxInstructionDefsValue;
}
/**
* @return Returns the maxPoints.
*/
public int getMaxPoints()
{
return maxPoints;
}
/**
* @param maxPointsValue The maxPoints to set.
*/
public void setMaxPoints(int maxPointsValue)
{
this.maxPoints = maxPointsValue;
}
/**
* @return Returns the maxSizeOfInstructions.
*/
public int getMaxSizeOfInstructions()
{
return maxSizeOfInstructions;
}
/**
* @param maxSizeOfInstructionsValue The maxSizeOfInstructions to set.
*/
public void setMaxSizeOfInstructions(int maxSizeOfInstructionsValue)
{
this.maxSizeOfInstructions = maxSizeOfInstructionsValue;
}
/**
* @return Returns the maxStackElements.
*/
public int getMaxStackElements()
{
return maxStackElements;
}
/**
* @param maxStackElementsValue The maxStackElements to set.
*/
public void setMaxStackElements(int maxStackElementsValue)
{
this.maxStackElements = maxStackElementsValue;
}
/**
* @return Returns the maxStorage.
*/
public int getMaxStorage()
{
return maxStorage;
}
/**
* @param maxStorageValue The maxStorage to set.
*/
public void setMaxStorage(int maxStorageValue)
{
this.maxStorage = maxStorageValue;
}
/**
* @return Returns the maxTwilightPoints.
*/
public int getMaxTwilightPoints()
{
return maxTwilightPoints;
}
/**
* @param maxTwilightPointsValue The maxTwilightPoints to set.
*/
public void setMaxTwilightPoints(int maxTwilightPointsValue)
{
this.maxTwilightPoints = maxTwilightPointsValue;
}
/**
* @return Returns the maxZones.
*/
public int getMaxZones()
{
return maxZones;
}
/**
* @param maxZonesValue The maxZones to set.
*/
public void setMaxZones(int maxZonesValue)
{
this.maxZones = maxZonesValue;
}
/**
* @return Returns the numGlyphs.
*/
public int getNumGlyphs()
{
return numGlyphs;
}
/**
* @param numGlyphsValue The numGlyphs to set.
*/
public void setNumGlyphs(int numGlyphsValue)
{
this.numGlyphs = numGlyphsValue;
}
/**
* @return Returns the version.
*/
public float getVersion()
{
return version;
}
/**
* @param versionValue The version to set.
*/
public void setVersion(float versionValue)
{
this.version = versionValue;
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
}
|
version = data.read32Fixed();
numGlyphs = data.readUnsignedShort();
if (version >= 1.0f)
{
maxPoints = data.readUnsignedShort();
maxContours = data.readUnsignedShort();
maxCompositePoints = data.readUnsignedShort();
maxCompositeContours = data.readUnsignedShort();
maxZones = data.readUnsignedShort();
maxTwilightPoints = data.readUnsignedShort();
maxStorage = data.readUnsignedShort();
maxFunctionDefs = data.readUnsignedShort();
maxInstructionDefs = data.readUnsignedShort();
maxStackElements = data.readUnsignedShort();
maxSizeOfInstructions = data.readUnsignedShort();
maxComponentElements = data.readUnsignedShort();
maxComponentDepth = data.readUnsignedShort();
}
initialized = true;
| 1,774
| 241
| 2,015
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/NameRecord.java
|
NameRecord
|
toString
|
class NameRecord
{
// platform ids
public static final int PLATFORM_UNICODE = 0;
public static final int PLATFORM_MACINTOSH = 1;
public static final int PLATFORM_ISO = 2;
public static final int PLATFORM_WINDOWS = 3;
// Unicode encoding ids
public static final int ENCODING_UNICODE_1_0 = 0;
public static final int ENCODING_UNICODE_1_1 = 1;
public static final int ENCODING_UNICODE_2_0_BMP = 3;
public static final int ENCODING_UNICODE_2_0_FULL = 4;
// Unicode encoding ids
public static final int LANGUAGE_UNICODE = 0;
// Windows encoding ids
public static final int ENCODING_WINDOWS_SYMBOL = 0;
public static final int ENCODING_WINDOWS_UNICODE_BMP = 1;
public static final int ENCODING_WINDOWS_UNICODE_UCS4 = 10;
// Windows language ids
public static final int LANGUAGE_WINDOWS_EN_US = 0x0409;
// Macintosh encoding ids
public static final int ENCODING_MACINTOSH_ROMAN = 0;
// Macintosh language ids
public static final int LANGUAGE_MACINTOSH_ENGLISH = 0;
// name ids
public static final int NAME_COPYRIGHT = 0;
public static final int NAME_FONT_FAMILY_NAME = 1;
public static final int NAME_FONT_SUB_FAMILY_NAME = 2;
public static final int NAME_UNIQUE_FONT_ID = 3;
public static final int NAME_FULL_FONT_NAME = 4;
public static final int NAME_VERSION = 5;
public static final int NAME_POSTSCRIPT_NAME = 6;
public static final int NAME_TRADEMARK = 7;
private int platformId;
private int platformEncodingId;
private int languageId;
private int nameId;
private int stringLength;
private int stringOffset;
private String string;
/**
* @return Returns the stringLength.
*/
public int getStringLength()
{
return stringLength;
}
/**
* @param stringLengthValue The stringLength to set.
*/
public void setStringLength(int stringLengthValue)
{
this.stringLength = stringLengthValue;
}
/**
* @return Returns the stringOffset.
*/
public int getStringOffset()
{
return stringOffset;
}
/**
* @param stringOffsetValue The stringOffset to set.
*/
public void setStringOffset(int stringOffsetValue)
{
this.stringOffset = stringOffsetValue;
}
/**
* @return Returns the languageId.
*/
public int getLanguageId()
{
return languageId;
}
/**
* @param languageIdValue The languageId to set.
*/
public void setLanguageId(int languageIdValue)
{
this.languageId = languageIdValue;
}
/**
* @return Returns the nameId.
*/
public int getNameId()
{
return nameId;
}
/**
* @param nameIdValue The nameId to set.
*/
public void setNameId(int nameIdValue)
{
this.nameId = nameIdValue;
}
/**
* @return Returns the platformEncodingId.
*/
public int getPlatformEncodingId()
{
return platformEncodingId;
}
/**
* @param platformEncodingIdValue The platformEncodingId to set.
*/
public void setPlatformEncodingId(int platformEncodingIdValue)
{
this.platformEncodingId = platformEncodingIdValue;
}
/**
* @return Returns the platformId.
*/
public int getPlatformId()
{
return platformId;
}
/**
* @param platformIdValue The platformId to set.
*/
public void setPlatformId(int platformIdValue)
{
this.platformId = platformIdValue;
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
void initData( TrueTypeFont ttf, TTFDataStream data ) throws IOException
{
platformId = data.readUnsignedShort();
platformEncodingId = data.readUnsignedShort();
languageId = data.readUnsignedShort();
nameId = data.readUnsignedShort();
stringLength = data.readUnsignedShort();
stringOffset = data.readUnsignedShort();
}
/**
* Return a string representation of this class.
*
* @return A string for this class.
*/
public String toString()
{<FILL_FUNCTION_BODY>}
/**
* @return Returns the string.
*/
public String getString()
{
return string;
}
/**
* @param stringValue The string to set.
*/
public void setString(String stringValue)
{
this.string = stringValue;
}
}
|
return
"platform=" + platformId +
" pEncoding=" + platformEncodingId +
" language=" + languageId +
" name=" + nameId +
" " + string;
| 1,417
| 56
| 1,473
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/OTFParser.java
|
OTFParser
|
readTable
|
class OTFParser extends TTFParser
{
/**
* Constructor.
*/
public OTFParser()
{
super();
}
/**
* Constructor.
*
* @param isEmbedded true if the font is embedded in PDF
*/
public OTFParser(boolean isEmbedded)
{
super(isEmbedded);
}
@Override
public OpenTypeFont parse(RandomAccessRead randomAccessRead) throws IOException
{
return (OpenTypeFont) super.parse(randomAccessRead);
}
@Override
OpenTypeFont parse(TTFDataStream raf) throws IOException
{
return (OpenTypeFont)super.parse(raf);
}
@Override
OpenTypeFont newFont(TTFDataStream raf)
{
return new OpenTypeFont(raf);
}
@Override
protected TTFTable readTable(String tag)
{<FILL_FUNCTION_BODY>}
@Override
protected boolean allowCFF()
{
return true;
}
}
|
// todo: this is a stub, a full implementation is needed
switch (tag)
{
case "BASE":
case "GDEF":
case "GPOS":
case GlyphSubstitutionTable.TAG:
case OTLTable.TAG:
return new OTLTable();
case CFFTable.TAG:
return new CFFTable();
default:
return super.readTable(tag);
}
| 284
| 110
| 394
|
<methods>public void <init>() ,public void <init>(boolean) ,public org.apache.fontbox.ttf.TrueTypeFont parse(org.apache.pdfbox.io.RandomAccessRead) throws java.io.IOException,public org.apache.fontbox.ttf.TrueTypeFont parseEmbedded(java.io.InputStream) throws java.io.IOException<variables>private static final Logger LOG,private boolean isEmbedded
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/OpenTypeFont.java
|
OpenTypeFont
|
isSupportedOTF
|
class OpenTypeFont extends TrueTypeFont
{
private boolean isPostScript;
/**
* Constructor. Clients should use the OTFParser to create a new OpenTypeFont object.
*
* @param fontData The font data.
*/
OpenTypeFont(TTFDataStream fontData)
{
super(fontData);
}
@Override
void setVersion(float versionValue)
{
isPostScript = Float.floatToIntBits(versionValue) == 0x469EA8A9; // OTTO
super.setVersion(versionValue);
}
/**
* Get the "CFF" table for this OTF.
*
* @return The "CFF" table.
*
* @throws IOException if the font data could not be read
* @throws UnsupportedOperationException if the current font isn't a CFF font
*/
public CFFTable getCFF() throws IOException
{
if (!isPostScript)
{
throw new UnsupportedOperationException("TTF fonts do not have a CFF table");
}
return (CFFTable) getTable(CFFTable.TAG);
}
@Override
public GlyphTable getGlyph() throws IOException
{
if (isPostScript)
{
throw new UnsupportedOperationException("OTF fonts do not have a glyf table");
}
return super.getGlyph();
}
@Override
public GeneralPath getPath(String name) throws IOException
{
if (isPostScript && isSupportedOTF())
{
int gid = nameToGID(name);
return getCFF().getFont().getType2CharString(gid).getPath();
}
else
{
return super.getPath(name);
}
}
/**
* Returns true if this font is a PostScript outline font.
*
* @return true if the font is a PostScript outline font, otherwise false
*/
public boolean isPostScript()
{
return isPostScript || tables.containsKey(CFFTable.TAG) || tables.containsKey("CFF2");
}
/**
* Returns true if this font is supported.
*
* There are 3 kind of OpenType fonts, fonts using TrueType outlines, fonts using CFF outlines (version 1 and 2)
*
* Fonts using CFF outlines version 2 aren't supported yet.
*
* @return true if the font is supported
*/
public boolean isSupportedOTF()
{<FILL_FUNCTION_BODY>}
/**
* Returns true if this font uses OpenType Layout (Advanced Typographic) tables.
*
* @return true if the font has any layout table, otherwise false
*/
public boolean hasLayoutTables()
{
return tables.containsKey("BASE") //
|| tables.containsKey("GDEF") //
|| tables.containsKey("GPOS") //
|| tables.containsKey(GlyphSubstitutionTable.TAG) //
|| tables.containsKey(OTLTable.TAG);
}
}
|
// OTF using CFF2 based outlines aren't yet supported
return !(isPostScript //
&& !tables.containsKey(CFFTable.TAG) //
&& tables.containsKey("CFF2") //
);
| 803
| 61
| 864
|
<methods>public void close() throws java.io.IOException,public void disableGsubFeature(java.lang.String) ,public void enableGsubFeature(java.lang.String) ,public void enableVerticalSubstitutions() ,public int getAdvanceHeight(int) throws java.io.IOException,public int getAdvanceWidth(int) throws java.io.IOException,public org.apache.fontbox.ttf.CmapTable getCmap() throws java.io.IOException,public org.apache.fontbox.util.BoundingBox getFontBBox() throws java.io.IOException,public List<java.lang.Number> getFontMatrix() throws java.io.IOException,public org.apache.fontbox.ttf.GlyphTable getGlyph() throws java.io.IOException,public org.apache.fontbox.ttf.GlyphSubstitutionTable getGsub() throws java.io.IOException,public org.apache.fontbox.ttf.model.GsubData getGsubData() throws java.io.IOException,public org.apache.fontbox.ttf.HeaderTable getHeader() throws java.io.IOException,public org.apache.fontbox.ttf.HorizontalHeaderTable getHorizontalHeader() throws java.io.IOException,public org.apache.fontbox.ttf.HorizontalMetricsTable getHorizontalMetrics() throws java.io.IOException,public org.apache.fontbox.ttf.IndexToLocationTable getIndexToLocation() throws java.io.IOException,public org.apache.fontbox.ttf.KerningTable getKerning() throws java.io.IOException,public org.apache.fontbox.ttf.MaximumProfileTable getMaximumProfile() throws java.io.IOException,public java.lang.String getName() throws java.io.IOException,public org.apache.fontbox.ttf.NamingTable getNaming() throws java.io.IOException,public int getNumberOfGlyphs() throws java.io.IOException,public org.apache.fontbox.ttf.OS2WindowsMetricsTable getOS2Windows() throws java.io.IOException,public java.io.InputStream getOriginalData() throws java.io.IOException,public long getOriginalDataSize() ,public java.awt.geom.GeneralPath getPath(java.lang.String) throws java.io.IOException,public org.apache.fontbox.ttf.PostScriptTable getPostScript() throws java.io.IOException,public byte[] getTableBytes(org.apache.fontbox.ttf.TTFTable) throws java.io.IOException,public Map<java.lang.String,org.apache.fontbox.ttf.TTFTable> getTableMap() ,public Collection<org.apache.fontbox.ttf.TTFTable> getTables() ,public org.apache.fontbox.ttf.CmapLookup getUnicodeCmapLookup() throws java.io.IOException,public org.apache.fontbox.ttf.CmapLookup getUnicodeCmapLookup(boolean) throws java.io.IOException,public int getUnitsPerEm() throws java.io.IOException,public float getVersion() ,public org.apache.fontbox.ttf.VerticalHeaderTable getVerticalHeader() throws java.io.IOException,public org.apache.fontbox.ttf.VerticalMetricsTable getVerticalMetrics() throws java.io.IOException,public org.apache.fontbox.ttf.VerticalOriginTable getVerticalOrigin() throws java.io.IOException,public float getWidth(java.lang.String) throws java.io.IOException,public boolean hasGlyph(java.lang.String) throws java.io.IOException,public int nameToGID(java.lang.String) throws java.io.IOException,public java.lang.String toString() <variables>private static final Logger LOG,private final non-sealed org.apache.fontbox.ttf.TTFDataStream data,private final List<java.lang.String> enabledGsubFeatures,private final java.lang.Object lockPSNames,private final java.lang.Object lockReadtable,private int numberOfGlyphs,private volatile Map<java.lang.String,java.lang.Integer> postScriptNames,protected final Map<java.lang.String,org.apache.fontbox.ttf.TTFTable> tables,private int unitsPerEm,private float version
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/RandomAccessReadDataStream.java
|
RandomAccessReadDataStream
|
seek
|
class RandomAccessReadDataStream extends TTFDataStream
{
private final long length;
private final byte[] data;
private int currentPosition = 0;
/**
* Constructor.
*
* @param randomAccessRead source to be read from
*
* @throws IOException If there is a problem reading the source data.
*/
RandomAccessReadDataStream(RandomAccessRead randomAccessRead) throws IOException
{
length = randomAccessRead.length();
data = new byte[(int) length];
int remainingBytes = data.length;
int amountRead;
while ((amountRead = randomAccessRead.read(data, data.length - remainingBytes,
remainingBytes)) > 0)
{
remainingBytes -= amountRead;
}
}
/**
* Constructor.
*
* @param inputStream source to be read from
*
* @throws IOException If there is a problem reading the source data.
*/
RandomAccessReadDataStream(InputStream inputStream) throws IOException
{
data = inputStream.readAllBytes();
length = data.length;
}
/**
* Get the current position in the stream.
* @return The current position in the stream.
* @throws IOException If an error occurs while reading the stream.
*/
@Override
public long getCurrentPosition() throws IOException
{
return currentPosition;
}
/**
* Close the underlying resources.
*
* @throws IOException If there is an error closing the resources.
*/
@Override
public void close() throws IOException
{
// nothing to do
}
/**
* Read an unsigned byte.
* @return An unsigned byte, or -1, signalling 'no more data'
* @throws IOException If there is an error reading the data.
*/
@Override
public int read() throws IOException
{
if (currentPosition >= length)
{
return -1;
}
return data[currentPosition++] & 0xff;
}
/**
* Read a signed 64-bit integer.
*
* @return eight bytes interpreted as a long.
* @throws IOException If there is an error reading the data.
*/
@Override
public final long readLong() throws IOException
{
return ((long) readInt() << 32) + (readInt() & 0xFFFFFFFFL);
}
/**
* Read a signed 32-bit integer.
*
* @return 4 bytes interpreted as an int.
* @throws IOException If there is an error reading the data.
*/
private int readInt() throws IOException
{
int b1 = read();
int b2 = read();
int b3 = read();
int b4 = read();
return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4;
}
/**
* Seek into the datasource.
* When the requested <code>pos</code> is < 0, an IOException() is fired.
* When the requested <code>pos</code> is ≥ {@link #length}, the {@link #currentPosition}
* is set to the first byte <i>after</i> the {@link #data}!
*
* @param pos The position to seek to.
* @throws IOException If there is an error seeking to that position.
*/
@Override
public void seek(long pos) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* @see java.io.InputStream#read( byte[], int, int )
*
* @param b The buffer to write to.
* @param off The offset into the buffer.
* @param len The length into the buffer.
*
* @return The number of bytes read or -1, signalling 'no more data'
*
* @throws IOException If there is an error reading from the stream.
*/
@Override
public int read(byte[] b, int off, int len) throws IOException
{
if (currentPosition >= length)
{
return -1;
}
int remainingBytes = (int) (length - currentPosition);
int bytesToRead = Math.min(remainingBytes, len);
System.arraycopy(data, currentPosition, b, off, bytesToRead);
currentPosition += bytesToRead;
return bytesToRead;
}
/**
* {@inheritDoc}
*/
@Override
public InputStream getOriginalData() throws IOException
{
return new ByteArrayInputStream(data);
}
/**
* {@inheritDoc}
*/
@Override
public long getOriginalDataSize()
{
return length;
}
}
|
if (pos < 0)
{
throw new IOException("Invalid position " + pos);
}
currentPosition = pos < length ? (int) pos : (int) length;
| 1,201
| 48
| 1,249
|
<methods>public abstract long getCurrentPosition() throws java.io.IOException,public abstract java.io.InputStream getOriginalData() throws java.io.IOException,public abstract long getOriginalDataSize() ,public abstract int read() throws java.io.IOException,public byte[] read(int) throws java.io.IOException,public abstract int read(byte[], int, int) throws java.io.IOException,public float read32Fixed() throws java.io.IOException,public java.util.Calendar readInternationalDate() throws java.io.IOException,public abstract long readLong() throws java.io.IOException,public int readSignedByte() throws java.io.IOException,public short readSignedShort() throws java.io.IOException,public java.lang.String readString(int) throws java.io.IOException,public java.lang.String readString(int, java.nio.charset.Charset) throws java.io.IOException,public java.lang.String readTag() throws java.io.IOException,public int readUnsignedByte() throws java.io.IOException,public int[] readUnsignedByteArray(int) throws java.io.IOException,public long readUnsignedInt() throws java.io.IOException,public int readUnsignedShort() throws java.io.IOException,public int[] readUnsignedShortArray(int) throws java.io.IOException,public abstract void seek(long) throws java.io.IOException<variables>private static final java.util.TimeZone TIMEZONE_UTC
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/SubstitutingCmapLookup.java
|
SubstitutingCmapLookup
|
getGlyphId
|
class SubstitutingCmapLookup implements CmapLookup
{
private final CmapSubtable cmap;
private final GlyphSubstitutionTable gsub;
private final List<String> enabledFeatures;
public SubstitutingCmapLookup(CmapSubtable cmap, GlyphSubstitutionTable gsub,
List<String> enabledFeatures)
{
this.cmap = cmap;
this.gsub = gsub;
this.enabledFeatures = enabledFeatures;
}
@Override
public int getGlyphId(int characterCode)
{<FILL_FUNCTION_BODY>}
@Override
public List<Integer> getCharCodes(int gid)
{
return cmap.getCharCodes(gsub.getUnsubstitution(gid));
}
}
|
int gid = cmap.getGlyphId(characterCode);
String[] scriptTags = OpenTypeScript.getScriptTags(characterCode);
return gsub.getSubstitution(gid, scriptTags, enabledFeatures);
| 208
| 58
| 266
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/TTCDataStream.java
|
TTCDataStream
|
close
|
class TTCDataStream extends TTFDataStream
{
private final TTFDataStream stream;
TTCDataStream(TTFDataStream stream)
{
this.stream = stream;
}
@Override
public int read() throws IOException
{
return stream.read();
}
@Override
public long readLong() throws IOException
{
return stream.readLong();
}
@Override
public void close() throws IOException
{<FILL_FUNCTION_BODY>}
@Override
public void seek(long pos) throws IOException
{
stream.seek(pos);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
return stream.read(b, off, len);
}
@Override
public long getCurrentPosition() throws IOException
{
return stream.getCurrentPosition();
}
@Override
public InputStream getOriginalData() throws IOException
{
return stream.getOriginalData();
}
@Override
public long getOriginalDataSize()
{
return stream.getOriginalDataSize();
}
}
|
// don't close the underlying stream, as it is shared by all fonts from the same TTC
// TrueTypeCollection.close() must be called instead
| 302
| 39
| 341
|
<methods>public abstract long getCurrentPosition() throws java.io.IOException,public abstract java.io.InputStream getOriginalData() throws java.io.IOException,public abstract long getOriginalDataSize() ,public abstract int read() throws java.io.IOException,public byte[] read(int) throws java.io.IOException,public abstract int read(byte[], int, int) throws java.io.IOException,public float read32Fixed() throws java.io.IOException,public java.util.Calendar readInternationalDate() throws java.io.IOException,public abstract long readLong() throws java.io.IOException,public int readSignedByte() throws java.io.IOException,public short readSignedShort() throws java.io.IOException,public java.lang.String readString(int) throws java.io.IOException,public java.lang.String readString(int, java.nio.charset.Charset) throws java.io.IOException,public java.lang.String readTag() throws java.io.IOException,public int readUnsignedByte() throws java.io.IOException,public int[] readUnsignedByteArray(int) throws java.io.IOException,public long readUnsignedInt() throws java.io.IOException,public int readUnsignedShort() throws java.io.IOException,public int[] readUnsignedShortArray(int) throws java.io.IOException,public abstract void seek(long) throws java.io.IOException<variables>private static final java.util.TimeZone TIMEZONE_UTC
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/TrueTypeCollection.java
|
TrueTypeCollection
|
getFontAtIndex
|
class TrueTypeCollection implements Closeable
{
private final TTFDataStream stream;
private final int numFonts;
private final long[] fontOffsets;
/**
* Creates a new TrueTypeCollection from a .ttc file.
*
* @param file The TTC file.
* @throws IOException If the font could not be parsed.
*/
public TrueTypeCollection(File file) throws IOException
{
this(new RandomAccessReadBufferedFile(file));
}
/**
* Creates a new TrueTypeCollection from a .ttc input stream.
*
* @param stream A TTC input stream.
* @throws IOException If the font could not be parsed.
*/
public TrueTypeCollection(InputStream stream) throws IOException
{
this(new RandomAccessReadBuffer(stream));
}
/**
* Creates a new TrueTypeCollection from a RandomAccessRead.
*
* @param randomAccessRead
* @throws IOException If the font could not be parsed.
*/
TrueTypeCollection(RandomAccessRead randomAccessRead) throws IOException
{
this.stream = new RandomAccessReadDataStream(randomAccessRead);
// TTC header
String tag = stream.readTag();
if (!tag.equals("ttcf"))
{
throw new IOException("Missing TTC header");
}
float version = stream.read32Fixed();
numFonts = (int)stream.readUnsignedInt();
if (numFonts <= 0 || numFonts > 1024)
{
throw new IOException("Invalid number of fonts " + numFonts);
}
fontOffsets = new long[numFonts];
for (int i = 0; i < numFonts; i++)
{
fontOffsets[i] = stream.readUnsignedInt();
}
if (version >= 2)
{
// not used at this time
int ulDsigTag = stream.readUnsignedShort();
int ulDsigLength = stream.readUnsignedShort();
int ulDsigOffset = stream.readUnsignedShort();
}
}
/**
* Run the callback for each TT font in the collection.
*
* @param trueTypeFontProcessor the object with the callback method.
* @throws IOException if something went wrong when calling the TrueTypeFontProcessor
*/
public void processAllFonts(TrueTypeFontProcessor trueTypeFontProcessor) throws IOException
{
for (int i = 0; i < numFonts; i++)
{
TrueTypeFont font = getFontAtIndex(i);
trueTypeFontProcessor.process(font);
}
}
private TrueTypeFont getFontAtIndex(int idx) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* Get a TT font from a collection.
*
* @param name The postscript name of the font.
* @return The found font, nor null if none is found.
* @throws IOException if there is an error reading the font data
*/
public TrueTypeFont getFontByName(String name) throws IOException
{
for (int i = 0; i < numFonts; i++)
{
TrueTypeFont font = getFontAtIndex(i);
if (font.getName().equals(name))
{
return font;
}
}
return null;
}
/**
* Implement the callback method to call {@link TrueTypeCollection#processAllFonts(TrueTypeFontProcessor)}.
*/
@FunctionalInterface
public interface TrueTypeFontProcessor
{
void process(TrueTypeFont ttf) throws IOException;
}
@Override
public void close() throws IOException
{
stream.close();
}
}
|
stream.seek(fontOffsets[idx]);
TTFParser parser;
if (stream.readTag().equals("OTTO"))
{
parser = new OTFParser(false);
}
else
{
parser = new TTFParser(false);
}
stream.seek(fontOffsets[idx]);
return parser.parse(new TTCDataStream(stream));
| 952
| 100
| 1,052
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/VerticalHeaderTable.java
|
VerticalHeaderTable
|
read
|
class VerticalHeaderTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "vhea";
private float version;
private short ascender;
private short descender;
private short lineGap;
private int advanceHeightMax;
private short minTopSideBearing;
private short minBottomSideBearing;
private short yMaxExtent;
private short caretSlopeRise;
private short caretSlopeRun;
private short caretOffset;
private short reserved1;
private short reserved2;
private short reserved3;
private short reserved4;
private short metricDataFormat;
private int numberOfVMetrics;
VerticalHeaderTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* @return Returns the advanceHeightMax.
*/
public int getAdvanceHeightMax()
{
return advanceHeightMax;
}
/**
* @return Returns the ascender.
*/
public short getAscender()
{
return ascender;
}
/**
* @return Returns the caretSlopeRise.
*/
public short getCaretSlopeRise()
{
return caretSlopeRise;
}
/**
* @return Returns the caretSlopeRun.
*/
public short getCaretSlopeRun()
{
return caretSlopeRun;
}
/**
* @return Returns the caretOffset.
*/
public short getCaretOffset()
{
return caretOffset;
}
/**
* @return Returns the descender.
*/
public short getDescender()
{
return descender;
}
/**
* @return Returns the lineGap.
*/
public short getLineGap()
{
return lineGap;
}
/**
* @return Returns the metricDataFormat.
*/
public short getMetricDataFormat()
{
return metricDataFormat;
}
/**
* @return Returns the minTopSideBearing.
*/
public short getMinTopSideBearing()
{
return minTopSideBearing;
}
/**
* @return Returns the minBottomSideBearing.
*/
public short getMinBottomSideBearing()
{
return minBottomSideBearing;
}
/**
* @return Returns the numberOfVMetrics.
*/
public int getNumberOfVMetrics()
{
return numberOfVMetrics;
}
/**
* @return Returns the reserved1.
*/
public short getReserved1()
{
return reserved1;
}
/**
* @return Returns the reserved2.
*/
public short getReserved2()
{
return reserved2;
}
/**
* @return Returns the reserved3.
*/
public short getReserved3()
{
return reserved3;
}
/**
* @return Returns the reserved4.
*/
public short getReserved4()
{
return reserved4;
}
/**
* @return Returns the version.
*/
public float getVersion()
{
return version;
}
/**
* @return Returns the yMaxExtent.
*/
public short getYMaxExtent()
{
return yMaxExtent;
}
}
|
version = data.read32Fixed();
ascender = data.readSignedShort();
descender = data.readSignedShort();
lineGap = data.readSignedShort();
advanceHeightMax = data.readUnsignedShort();
minTopSideBearing = data.readSignedShort();
minBottomSideBearing = data.readSignedShort();
yMaxExtent = data.readSignedShort();
caretSlopeRise = data.readSignedShort();
caretSlopeRun = data.readSignedShort();
caretOffset = data.readSignedShort();
reserved1 = data.readSignedShort();
reserved2 = data.readSignedShort();
reserved3 = data.readSignedShort();
reserved4 = data.readSignedShort();
metricDataFormat = data.readSignedShort();
numberOfVMetrics = data.readUnsignedShort();
initialized = true;
| 993
| 235
| 1,228
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/VerticalMetricsTable.java
|
VerticalMetricsTable
|
getAdvanceHeight
|
class VerticalMetricsTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "vmtx";
private int[] advanceHeight;
private short[] topSideBearing;
private short[] additionalTopSideBearing;
private int numVMetrics;
VerticalMetricsTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{
VerticalHeaderTable vHeader = ttf.getVerticalHeader();
if (vHeader == null)
{
throw new IOException("Could not get vhea table");
}
numVMetrics = vHeader.getNumberOfVMetrics();
int numGlyphs = ttf.getNumberOfGlyphs();
int bytesRead = 0;
advanceHeight = new int[ numVMetrics ];
topSideBearing = new short[ numVMetrics ];
for( int i=0; i<numVMetrics; i++ )
{
advanceHeight[i] = data.readUnsignedShort();
topSideBearing[i] = data.readSignedShort();
bytesRead += 4;
}
if (bytesRead < getLength())
{
int numberNonVertical = numGlyphs - numVMetrics;
// handle bad fonts with too many vmetrics
if (numberNonVertical < 0)
{
numberNonVertical = numGlyphs;
}
additionalTopSideBearing = new short[numberNonVertical];
for( int i=0; i<numberNonVertical; i++ )
{
if (bytesRead < getLength())
{
additionalTopSideBearing[i] = data.readSignedShort();
bytesRead += 2;
}
}
}
initialized = true;
}
/**
* Returns the top sidebearing for the given GID
*
* @param gid GID
* @return top sidebearing for the given GID
*
*/
public int getTopSideBearing(int gid)
{
if (gid < numVMetrics)
{
return topSideBearing[gid];
}
else
{
return additionalTopSideBearing[gid - numVMetrics];
}
}
/**
* Returns the advance height for the given GID.
*
* @param gid GID
* @return advance height for the given GID
*/
public int getAdvanceHeight(int gid)
{<FILL_FUNCTION_BODY>}
}
|
if (gid < numVMetrics)
{
return advanceHeight[gid];
}
else
{
// monospaced fonts may not have a height for every glyph
// the last one is for subsequent glyphs
return advanceHeight[advanceHeight.length -1];
}
| 742
| 80
| 822
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/VerticalOriginTable.java
|
VerticalOriginTable
|
read
|
class VerticalOriginTable extends TTFTable
{
/**
* A tag that identifies this table type.
*/
public static final String TAG = "VORG";
private float version;
private int defaultVertOriginY;
private Map<Integer, Integer> origins;
VerticalOriginTable()
{
super();
}
/**
* This will read the required data from the stream.
*
* @param ttf The font that is being read.
* @param data The stream to read the data from.
* @throws IOException If there is an error reading the data.
*/
@Override
void read(TrueTypeFont ttf, TTFDataStream data) throws IOException
{<FILL_FUNCTION_BODY>}
/**
* @return Returns the version.
*/
public float getVersion()
{
return version;
}
/**
* Returns the y-coordinate of the vertical origin for the given GID if known,
* or returns the default value if not specified in table data.
*
* @param gid GID
* @return Returns the y-coordinate of the vertical origin.
*/
public int getOriginY(int gid)
{
if (origins.containsKey(gid))
{
return origins.get(gid);
}
else
{
return defaultVertOriginY;
}
}
}
|
version = data.read32Fixed();
defaultVertOriginY = data.readSignedShort();
int numVertOriginYMetrics = data.readUnsignedShort();
origins = new ConcurrentHashMap<>(numVertOriginYMetrics);
for (int i = 0; i < numVertOriginYMetrics; ++i)
{
int g = data.readUnsignedShort();
int y = data.readSignedShort();
origins.put(g, y);
}
initialized = true;
| 371
| 132
| 503
|
<methods>public long getCheckSum() ,public boolean getInitialized() ,public long getLength() ,public long getOffset() ,public java.lang.String getTag() <variables>private long checkSum,protected boolean initialized,private long length,private long offset,private java.lang.String tag
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/WGL4Names.java
|
WGL4Names
|
getAllNames
|
class WGL4Names
{
/**
* The number of standard mac glyph names.
*/
public static final int NUMBER_OF_MAC_GLYPHS = 258;
/**
* The 258 standard mac glyph names a used in 'post' format 1 and 2.
*/
private static final String[] MAC_GLYPH_NAMES = {
".notdef",".null", "nonmarkingreturn", "space", "exclam", "quotedbl",
"numbersign", "dollar", "percent", "ampersand", "quotesingle",
"parenleft", "parenright", "asterisk", "plus", "comma", "hyphen",
"period", "slash", "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "colon", "semicolon", "less",
"equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F",
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash",
"bracketright", "asciicircum", "underscore", "grave", "a", "b",
"c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
"p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft",
"bar", "braceright", "asciitilde", "Adieresis", "Aring",
"Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute",
"agrave", "acircumflex", "adieresis", "atilde", "aring",
"ccedilla", "eacute", "egrave", "ecircumflex", "edieresis",
"iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute",
"ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave",
"ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling",
"section", "bullet", "paragraph", "germandbls", "registered",
"copyright", "trademark", "acute", "dieresis", "notequal", "AE",
"Oslash", "infinity", "plusminus", "lessequal", "greaterequal",
"yen", "mu", "partialdiff", "summation", "product", "pi",
"integral", "ordfeminine", "ordmasculine", "Omega", "ae", "oslash",
"questiondown", "exclamdown", "logicalnot", "radical", "florin",
"approxequal", "Delta", "guillemotleft", "guillemotright",
"ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE",
"oe", "endash", "emdash", "quotedblleft", "quotedblright",
"quoteleft", "quoteright", "divide", "lozenge", "ydieresis",
"Ydieresis", "fraction", "currency", "guilsinglleft",
"guilsinglright", "fi", "fl", "daggerdbl", "periodcentered",
"quotesinglbase", "quotedblbase", "perthousand", "Acircumflex",
"Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute",
"Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex",
"apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi",
"circumflex", "tilde", "macron", "breve", "dotaccent", "ring",
"cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash",
"Scaron", "scaron", "Zcaron", "zcaron", "brokenbar", "Eth", "eth",
"Yacute", "yacute", "Thorn", "thorn", "minus", "multiply",
"onesuperior", "twosuperior", "threesuperior", "onehalf",
"onequarter", "threequarters", "franc", "Gbreve", "gbreve",
"Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute", "Ccaron",
"ccaron", "dcroat"
};
/**
* The indices of the standard mac glyph names.
*/
private static final Map<String, Integer> MAC_GLYPH_NAMES_INDICES;
static
{
MAC_GLYPH_NAMES_INDICES = new HashMap<>(NUMBER_OF_MAC_GLYPHS);
for (int i = 0; i < NUMBER_OF_MAC_GLYPHS; ++i)
{
MAC_GLYPH_NAMES_INDICES.put(MAC_GLYPH_NAMES[i],i);
}
}
private WGL4Names()
{
}
/**
* Returns the index of the glyph with the given name.
*
* @param name the name of the glyph
* @return the index of the given glyph name or null for an invalid glyph name
*/
public static Integer getGlyphIndex(String name)
{
return MAC_GLYPH_NAMES_INDICES.get(name);
}
/**
* Returns the name of the glyph at the given index.
*
* @param index the index of the glyph
* @return the name of the glyph at the given index or null fo an invalid glyph index
*/
public static String getGlyphName(int index)
{
return index >= 0 && index < NUMBER_OF_MAC_GLYPHS ? MAC_GLYPH_NAMES[index] : null;
}
/**
* Returns a new array with all glyph names.
*
* @return the array with all glyph names
*/
public static String[] getAllNames()
{<FILL_FUNCTION_BODY>}
}
|
String[] glyphNames = new String[NUMBER_OF_MAC_GLYPHS];
System.arraycopy(MAC_GLYPH_NAMES, 0, glyphNames, 0, NUMBER_OF_MAC_GLYPHS);
return glyphNames;
| 1,814
| 76
| 1,890
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/gsub/CompoundCharacterTokenizer.java
|
CompoundCharacterTokenizer
|
tokenize
|
class CompoundCharacterTokenizer
{
private final Pattern regexExpression;
/**
* Constructor. Calls getRegexFromTokens which returns strings like
* (_79_99_)|(_80_99_)|(_92_99_) and creates a regexp assigned to regexExpression. See the code
* in GlyphArraySplitterRegexImpl on how these strings were created.
*
* @param compoundWords A set of strings like _79_99_, _80_99_ or _92_99_ .
*/
public CompoundCharacterTokenizer(Set<String> compoundWords)
{
regexExpression = Pattern.compile(getRegexFromTokens(compoundWords));
}
public CompoundCharacterTokenizer(Pattern pattern)
{
regexExpression = pattern;
}
public List<String> tokenize(String text)
{<FILL_FUNCTION_BODY>}
private String getRegexFromTokens(Set<String> compoundWords)
{
StringJoiner sj = new StringJoiner(")|(", "(", ")");
compoundWords.forEach(sj::add);
return sj.toString();
}
}
|
List<String> tokens = new ArrayList<>();
Matcher regexMatcher = regexExpression.matcher(text);
int lastIndexOfPrevMatch = 0;
while (regexMatcher.find()) // this is where the magic happens:
// the regexp is used to find a matching pattern for substitution
{
int beginIndexOfNextMatch = regexMatcher.start();
String prevToken = text.substring(lastIndexOfPrevMatch, beginIndexOfNextMatch);
if (!prevToken.isEmpty())
{
tokens.add(prevToken);
}
String currentMatch = regexMatcher.group();
tokens.add(currentMatch);
lastIndexOfPrevMatch = regexMatcher.end();
}
String tail = text.substring(lastIndexOfPrevMatch);
if (!tail.isEmpty())
{
tokens.add(tail);
}
return tokens;
| 312
| 234
| 546
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/gsub/DefaultGsubWorker.java
|
DefaultGsubWorker
|
applyTransforms
|
class DefaultGsubWorker implements GsubWorker
{
private static final Logger LOG = LogManager.getLogger(DefaultGsubWorker.class);
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{<FILL_FUNCTION_BODY>}
}
|
LOG.warn(
"{} class does not perform actual GSUB substitutions. Perhaps the selected language is not yet supported by the FontBox library.",
getClass().getSimpleName());
// Make the result read-only to prevent accidental modifications of the source list
return Collections.unmodifiableList(originalGlyphIds);
| 79
| 81
| 160
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/gsub/GlyphArraySplitterRegexImpl.java
|
GlyphArraySplitterRegexImpl
|
getMatchersAsStrings
|
class GlyphArraySplitterRegexImpl implements GlyphArraySplitter
{
private static final String GLYPH_ID_SEPARATOR = "_";
private final CompoundCharacterTokenizer compoundCharacterTokenizer;
public GlyphArraySplitterRegexImpl(Set<List<Integer>> matchers)
{
compoundCharacterTokenizer = new CompoundCharacterTokenizer(getMatchersAsStrings(matchers));
}
@Override
public List<List<Integer>> split(List<Integer> glyphIds)
{
String originalGlyphsAsText = convertGlyphIdsToString(glyphIds);
List<String> tokens = compoundCharacterTokenizer.tokenize(originalGlyphsAsText);
List<List<Integer>> modifiedGlyphs = new ArrayList<>(tokens.size());
tokens.forEach(token -> modifiedGlyphs.add(convertGlyphIdsToList(token)));
return modifiedGlyphs;
}
private Set<String> getMatchersAsStrings(Set<List<Integer>> matchers)
{<FILL_FUNCTION_BODY>}
private String convertGlyphIdsToString(List<Integer> glyphIds)
{
StringBuilder sb = new StringBuilder(20);
sb.append(GLYPH_ID_SEPARATOR);
glyphIds.forEach(glyphId -> sb.append(glyphId).append(GLYPH_ID_SEPARATOR));
return sb.toString();
}
private List<Integer> convertGlyphIdsToList(String glyphIdsAsString)
{
List<Integer> gsubProcessedGlyphsIds = new ArrayList<>();
for (String glyphId : glyphIdsAsString.split(GLYPH_ID_SEPARATOR))
{
glyphId = glyphId.trim();
if (glyphId.isEmpty())
{
continue;
}
gsubProcessedGlyphsIds.add(Integer.valueOf(glyphId));
}
return gsubProcessedGlyphsIds;
}
}
|
Set<String> stringMatchers = new TreeSet<>((String s1, String s2) ->
{
// comparator to ensure that strings with the same beginning
// put the larger string first
if (s1.length() == s2.length())
{
return s2.compareTo(s1);
}
return s2.length() - s1.length();
});
matchers.forEach(glyphIds -> stringMatchers.add(convertGlyphIdsToString(glyphIds)));
return stringMatchers;
| 516
| 138
| 654
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/gsub/GsubWorkerFactory.java
|
GsubWorkerFactory
|
getGsubWorker
|
class GsubWorkerFactory
{
private static final Logger LOG = LogManager.getLogger(GsubWorkerFactory.class);
public GsubWorker getGsubWorker(CmapLookup cmapLookup, GsubData gsubData)
{<FILL_FUNCTION_BODY>}
}
|
//TODO this needs to be redesigned / improved because if a font supports several languages,
// it will choose one of them and maybe not the one expected.
LOG.debug("Language: {}", gsubData.getLanguage());
switch (gsubData.getLanguage())
{
case BENGALI:
return new GsubWorkerForBengali(cmapLookup, gsubData);
case DEVANAGARI:
return new GsubWorkerForDevanagari(cmapLookup, gsubData);
case GUJARATI:
return new GsubWorkerForGujarati(cmapLookup, gsubData);
case LATIN:
return new GsubWorkerForLatin(cmapLookup, gsubData);
default:
return new DefaultGsubWorker();
}
| 79
| 213
| 292
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/gsub/GsubWorkerForLatin.java
|
GsubWorkerForLatin
|
applyGsubFeature
|
class GsubWorkerForLatin implements GsubWorker
{
private static final Logger LOG = LogManager.getLogger(GsubWorkerForLatin.class);
/**
* This sequence is very important. This has been taken from <a href=
* "https://docs.microsoft.com/en-us/typography/script-development/standard">https://docs.microsoft.com/en-us/typography/script-development/standard</a>
*/
private static final List<String> FEATURES_IN_ORDER = Arrays.asList("ccmp", "liga", "clig");
private final CmapLookup cmapLookup;
private final GsubData gsubData;
GsubWorkerForLatin(CmapLookup cmapLookup, GsubData gsubData)
{
this.cmapLookup = cmapLookup;
this.gsubData = gsubData;
}
@Override
public List<Integer> applyTransforms(List<Integer> originalGlyphIds)
{
List<Integer> intermediateGlyphsFromGsub = originalGlyphIds;
for (String feature : FEATURES_IN_ORDER)
{
if (!gsubData.isFeatureSupported(feature))
{
LOG.debug("the feature {} was not found", feature);
continue;
}
LOG.debug("applying the feature {}", feature);
ScriptFeature scriptFeature = gsubData.getFeature(feature);
intermediateGlyphsFromGsub = applyGsubFeature(scriptFeature,
intermediateGlyphsFromGsub);
}
return Collections.unmodifiableList(intermediateGlyphsFromGsub);
}
private List<Integer> applyGsubFeature(ScriptFeature scriptFeature,
List<Integer> originalGlyphs)
{<FILL_FUNCTION_BODY>}
}
|
if (scriptFeature.getAllGlyphIdsForSubstitution().isEmpty())
{
LOG.debug("getAllGlyphIdsForSubstitution() for {} is empty",
scriptFeature.getName());
return originalGlyphs;
}
GlyphArraySplitter glyphArraySplitter = new GlyphArraySplitterRegexImpl(
scriptFeature.getAllGlyphIdsForSubstitution());
List<List<Integer>> tokens = glyphArraySplitter.split(originalGlyphs);
List<Integer> gsubProcessedGlyphs = new ArrayList<>();
for (List<Integer> chunk : tokens)
{
if (scriptFeature.canReplaceGlyphs(chunk))
{
// gsub system kicks in, you get the glyphId directly
int glyphId = scriptFeature.getReplacementForGlyphs(chunk);
gsubProcessedGlyphs.add(glyphId);
}
else
{
gsubProcessedGlyphs.addAll(chunk);
}
}
LOG.debug("originalGlyphs: {}, gsubProcessedGlyphs: {}", originalGlyphs, gsubProcessedGlyphs);
return gsubProcessedGlyphs;
| 473
| 314
| 787
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/model/MapBackedGsubData.java
|
MapBackedGsubData
|
getFeature
|
class MapBackedGsubData implements GsubData
{
private final Language language;
private final String activeScriptName;
private final Map<String, Map<List<Integer>, Integer>> glyphSubstitutionMap;
public MapBackedGsubData(Language language, String activeScriptName,
Map<String, Map<List<Integer>, Integer>> glyphSubstitutionMap)
{
this.language = language;
this.activeScriptName = activeScriptName;
this.glyphSubstitutionMap = glyphSubstitutionMap;
}
@Override
public Language getLanguage()
{
return language;
}
@Override
public String getActiveScriptName()
{
return activeScriptName;
}
@Override
public boolean isFeatureSupported(String featureName)
{
return glyphSubstitutionMap.containsKey(featureName);
}
@Override
public ScriptFeature getFeature(String featureName)
{<FILL_FUNCTION_BODY>}
@Override
public Set<String> getSupportedFeatures()
{
return glyphSubstitutionMap.keySet();
}
}
|
if (!isFeatureSupported(featureName))
{
throw new UnsupportedOperationException(
"The feature " + featureName + " is not supported!");
}
return new MapBackedScriptFeature(featureName, glyphSubstitutionMap.get(featureName));
| 301
| 72
| 373
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/model/MapBackedScriptFeature.java
|
MapBackedScriptFeature
|
equals
|
class MapBackedScriptFeature implements ScriptFeature
{
private final String name;
private final Map<List<Integer>, Integer> featureMap;
public MapBackedScriptFeature(String name, Map<List<Integer>, Integer> featureMap)
{
this.name = name;
this.featureMap = featureMap;
}
@Override
public String getName()
{
return name;
}
@Override
public Set<List<Integer>> getAllGlyphIdsForSubstitution()
{
return featureMap.keySet();
}
@Override
public boolean canReplaceGlyphs(List<Integer> glyphIds)
{
return featureMap.containsKey(glyphIds);
}
@Override
public Integer getReplacementForGlyphs(List<Integer> glyphIds)
{
if (!canReplaceGlyphs(glyphIds))
{
throw new UnsupportedOperationException(
"The glyphs " + glyphIds + " cannot be replaced");
}
return featureMap.get(glyphIds);
}
@Override
public int hashCode()
{
return Objects.hash(featureMap, name);
}
@Override
public boolean equals(Object obj)
{<FILL_FUNCTION_BODY>}
}
|
if (this == obj)
{
return true;
}
if (obj == null || getClass() != obj.getClass())
{
return false;
}
MapBackedScriptFeature other = (MapBackedScriptFeature) obj;
return Objects.equals(other.name, this.name) && Objects.equals(other.featureMap, this.featureMap);
| 341
| 101
| 442
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/table/common/CoverageTableFormat2.java
|
CoverageTableFormat2
|
getRangeRecordsAsArray
|
class CoverageTableFormat2 extends CoverageTableFormat1
{
private final RangeRecord[] rangeRecords;
public CoverageTableFormat2(int coverageFormat, RangeRecord[] rangeRecords)
{
super(coverageFormat, getRangeRecordsAsArray(rangeRecords));
this.rangeRecords = rangeRecords;
}
public RangeRecord[] getRangeRecords()
{
return rangeRecords;
}
private static int[] getRangeRecordsAsArray(RangeRecord[] rangeRecords)
{<FILL_FUNCTION_BODY>}
@Override
public String toString()
{
return String.format("CoverageTableFormat2[coverageFormat=%d]", getCoverageFormat());
}
}
|
List<Integer> glyphIds = new ArrayList<>();
for (RangeRecord rangeRecord : rangeRecords)
{
for (int glyphId = rangeRecord.getStartGlyphID(); glyphId <= rangeRecord.getEndGlyphID(); glyphId++)
{
glyphIds.add(glyphId);
}
}
int[] glyphArray = new int[glyphIds.size()];
for (int i = 0; i < glyphArray.length; i++)
{
glyphArray[i] = glyphIds.get(i);
}
return glyphArray;
| 193
| 162
| 355
|
<methods>public void <init>(int, int[]) ,public int getCoverageIndex(int) ,public int[] getGlyphArray() ,public int getGlyphId(int) ,public int getSize() ,public java.lang.String toString() <variables>private final non-sealed int[] glyphArray
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/table/gsub/LookupTypeSingleSubstFormat1.java
|
LookupTypeSingleSubstFormat1
|
doSubstitution
|
class LookupTypeSingleSubstFormat1 extends LookupSubTable
{
private final short deltaGlyphID;
public LookupTypeSingleSubstFormat1(int substFormat, CoverageTable coverageTable,
short deltaGlyphID)
{
super(substFormat, coverageTable);
this.deltaGlyphID = deltaGlyphID;
}
@Override
public int doSubstitution(int gid, int coverageIndex)
{<FILL_FUNCTION_BODY>}
public short getDeltaGlyphID()
{
return deltaGlyphID;
}
@Override
public String toString()
{
return String.format("LookupTypeSingleSubstFormat1[substFormat=%d,deltaGlyphID=%d]",
getSubstFormat(), deltaGlyphID);
}
}
|
return coverageIndex < 0 ? gid : gid + deltaGlyphID;
| 213
| 22
| 235
|
<methods>public void <init>(int, org.apache.fontbox.ttf.table.common.CoverageTable) ,public abstract int doSubstitution(int, int) ,public org.apache.fontbox.ttf.table.common.CoverageTable getCoverageTable() ,public int getSubstFormat() <variables>private final non-sealed org.apache.fontbox.ttf.table.common.CoverageTable coverageTable,private final non-sealed int substFormat
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/ttf/table/gsub/SequenceTable.java
|
SequenceTable
|
toString
|
class SequenceTable
{
private final int glyphCount;
private final int[] substituteGlyphIDs;
public SequenceTable(int glyphCount, int[] substituteGlyphIDs)
{
this.glyphCount = glyphCount;
this.substituteGlyphIDs = substituteGlyphIDs;
}
public int getGlyphCount()
{
return glyphCount;
}
public int[] getSubstituteGlyphIDs()
{
return substituteGlyphIDs;
}
@Override
public String toString()
{<FILL_FUNCTION_BODY>}
}
|
return "SequenceTable{" + "glyphCount=" + glyphCount + ", substituteGlyphIDs=" + Arrays.toString(substituteGlyphIDs) + '}';
| 166
| 47
| 213
|
<no_super_class>
|
apache_pdfbox
|
pdfbox/fontbox/src/main/java/org/apache/fontbox/type1/Token.java
|
Token
|
toString
|
class Token
{
/**
* All different types of tokens.
*
*/
enum Kind
{
NONE, STRING, NAME, LITERAL, REAL, INTEGER,
START_ARRAY, END_ARRAY,
START_PROC, END_PROC,
START_DICT, END_DICT,
CHARSTRING
}
// exposed statically for convenience
static final Kind STRING = Kind.STRING;
static final Kind NAME = Kind.NAME;
static final Kind LITERAL = Kind.LITERAL;
static final Kind REAL = Kind.REAL;
static final Kind INTEGER = Kind.INTEGER;
static final Kind START_ARRAY = Kind.START_ARRAY;
static final Kind END_ARRAY = Kind.END_ARRAY;
static final Kind START_PROC = Kind.START_PROC;
static final Kind END_PROC = Kind.END_PROC;
static final Kind CHARSTRING = Kind.CHARSTRING;
static final Kind START_DICT = Kind.START_DICT;
static final Kind END_DICT = Kind.END_DICT;
private String text;
private byte[] data;
private final Kind kind;
/**
* Constructs a new Token object given its text and kind.
* @param text
* @param type
*/
Token(String text, Kind type)
{
this.text = text;
this.kind = type;
}
/**
* Constructs a new Token object given its single-character text and kind.
* @param character
* @param type
*/
Token(char character, Kind type)
{
this.text = Character.toString(character);
this.kind = type;
}
/**
* Constructs a new Token object given its raw data and kind.
* This is for CHARSTRING tokens only.
* @param data
* @param type
*/
Token(byte[] data, Kind type)
{
this.data = data;
this.kind = type;
}
public String getText()
{
return text;
}
public Kind getKind()
{
return kind;
}
public int intValue()
{
// some fonts have reals where integers should be, so we tolerate it
return (int)Float.parseFloat(text);
}
public float floatValue()
{
return Float.parseFloat(text);
}
public boolean booleanValue()
{
return text.equals("true");
}
public byte[] getData()
{
return data;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{<FILL_FUNCTION_BODY>}
}
|
if (kind == CHARSTRING)
{
return "Token[kind=CHARSTRING, data=" + data.length + " bytes]";
}
else
{
return "Token[kind=" + kind + ", text=" + text + "]";
}
| 727
| 72
| 799
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.