本文整理汇总了Java中org.apache.pdfbox.cos.COSDictionary类的典型用法代码示例。如果您正苦于以下问题:Java COSDictionary类的具体用法?Java COSDictionary怎么用?Java COSDictionary使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
COSDictionary类属于org.apache.pdfbox.cos包,在下文中一共展示了COSDictionary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testRenderSdnList
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
* Render Type3 font character as image using PDFBox
* </a>
* <br/>
* <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
* 4700198773.pdf
* </a>
* from
* <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
* extract text with custom font result non readble
* </a>
* <p>
* This test shows how one can render individual Type 3 font glyphs as bitmaps.
* Unfortunately PDFBox out-of-the-box does not provide a class to render contents
* of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
* with the glyph in question and render that page.
* </p>
* <p>
* As the OP did not provide a sample PDF, we simply use one from another
* stackoverflow question. There obviously might remain issues with the
* OP's files.
* </p>
*/
@Test
public void testRenderSdnList() throws IOException
{
try ( InputStream resource = getClass().getResourceAsStream("sdnlist.pdf"))
{
PDDocument document = PDDocument.load(resource);
PDPage page = document.getPage(1);
PDResources pageResources = page.getResources();
COSName f1Name = COSName.getPDFName("R144");
PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();
COSDictionary charProcsDictionary = fontF1.getCharProcs();
for (COSName key : charProcsDictionary.keySet())
{
COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
PDRectangle bbox = charProc.getGlyphBBox();
if (bbox == null)
bbox = charProc.getBBox();
Integer code = f1NameToCode.get(key.getName());
if (code != null)
{
PDDocument charDocument = new PDDocument();
PDPage charPage = new PDPage(bbox);
charDocument.addPage(charPage);
charPage.setResources(pageResources);
PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
charContentStream.beginText();
charContentStream.setFont(fontF1, bbox.getHeight());
charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
charContentStream.endText();
charContentStream.close();
File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code));
PDFRenderer renderer = new PDFRenderer(charDocument);
BufferedImage image = renderer.renderImageWithDPI(0, 96);
ImageIO.write(image, "PNG", result);
charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code)));
charDocument.close();
}
}
}
}
示例2: testRemoveLikeStephanImproved
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="https://stackoverflow.com/questions/45812696/pdfbox-delete-comment-maintain-strikethrough">
* PDFBox delete comment maintain strikethrough
* </a>
* <br/>
* <a href="https://expirebox.com/files/3d955e6df4ca5874c38dbf92fc43b5af.pdf">
* only_fields.pdf
* </a>
* <a href="https://file.io/DTvqhC">
* (alternative download)
* </a>
* <p>
* The OP only wanted the comment removed, not the strike-through. Thus, we must
* not remove the annotation but merely the comment building attributes.
* </p>
*/
@Test
public void testRemoveLikeStephanImproved() throws IOException {
final COSName POPUP = COSName.getPDFName("Popup");
try (InputStream resource = getClass().getResourceAsStream("only_fields.pdf")) {
PDDocument document = PDDocument.load(resource);
List<PDAnnotation> annotations = new ArrayList<>();
PDPageTree allPages = document.getDocumentCatalog().getPages();
List<COSObjectable> objectsToRemove = new ArrayList<>();
for (int i = 0; i < allPages.getCount(); i++) {
PDPage page = allPages.get(i);
annotations = page.getAnnotations();
for (PDAnnotation annotation : annotations) {
if ("StrikeOut".equals(annotation.getSubtype()))
{
COSDictionary annotationDict = annotation.getCOSObject();
COSBase popup = annotationDict.getItem(POPUP);
annotationDict.removeItem(POPUP);
annotationDict.removeItem(COSName.CONTENTS); // plain text comment
annotationDict.removeItem(COSName.RC); // rich text comment
annotationDict.removeItem(COSName.T); // author
if (popup != null)
objectsToRemove.add(popup);
}
}
annotations.removeAll(objectsToRemove);
}
document.save(new File(RESULT_FOLDER, "only_fields-removeImproved.pdf"));
}
}
示例3: testRender4700198773
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
* Render Type3 font character as image using PDFBox
* </a>
* <br/>
* <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
* 4700198773.pdf
* </a>
* from
* <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
* extract text with custom font result non readble
* </a>
* <p>
* This test shows how one can render individual Type 3 font glyphs as bitmaps.
* Unfortunately PDFBox out-of-the-box does not provide a class to render contents
* of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
* with the glyph in question and render that page.
* </p>
* <p>
* As the OP did not provide a sample PDF, we simply use one from another
* stackoverflow question. There obviously might remain issues with the
* OP's files.
* </p>
*/
@Test
public void testRender4700198773() throws IOException
{
try ( InputStream resource = getClass().getResourceAsStream("4700198773.pdf"))
{
PDDocument document = PDDocument.load(resource);
PDPage page = document.getPage(0);
PDResources pageResources = page.getResources();
COSName f1Name = COSName.getPDFName("F1");
PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();
COSDictionary charProcsDictionary = fontF1.getCharProcs();
for (COSName key : charProcsDictionary.keySet())
{
COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
PDRectangle bbox = charProc.getGlyphBBox();
if (bbox == null)
bbox = charProc.getBBox();
Integer code = f1NameToCode.get(key.getName());
if (code != null)
{
PDDocument charDocument = new PDDocument();
PDPage charPage = new PDPage(bbox);
charDocument.addPage(charPage);
charPage.setResources(pageResources);
PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
charContentStream.beginText();
charContentStream.setFont(fontF1, bbox.getHeight());
charContentStream.getOutput().write(String.format("<%2X> Tj\n", code).getBytes());
charContentStream.endText();
charContentStream.close();
File result = new File(RESULT_FOLDER, String.format("4700198773-%s-%s.png", key.getName(), code));
PDFRenderer renderer = new PDFRenderer(charDocument);
BufferedImage image = renderer.renderImageWithDPI(0, 96);
ImageIO.write(image, "PNG", result);
charDocument.save(new File(RESULT_FOLDER, String.format("4700198773-%s-%s.pdf", key.getName(), code)));
charDocument.close();
}
}
}
}
示例4: writeInputFieldToPDFPage
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/43604973/creating-a-checkbox-and-printing-it-to-pdf-file-is-not-working-using-pdfbox-1-8">
* Creating a checkbox and printing it to pdf file is not working using pdfbox 1.8.9 api
* </a>
* <p>
* The OP's method for checkbox creation.
* </p>
* @see #testCheckboxLikeSureshGoud()
*/
public static void writeInputFieldToPDFPage( PDPage pdPage, PDDocument document, Float x, Float y, Boolean ticked) throws IOException {
PDFont font = PDType1Font.HELVETICA;
PDResources res = new PDResources();
String fontName = res.addFont(font);
String da = ticked?"/" + fontName + " 10 Tf 0 0.4 0 rg":"";
COSDictionary acroFormDict = new COSDictionary();
acroFormDict.setBoolean(COSName.getPDFName("NeedAppearances"), true);
acroFormDict.setItem(COSName.FIELDS, new COSArray());
acroFormDict.setItem(COSName.DA, new COSString(da));
PDAcroForm acroForm = new PDAcroForm(document, acroFormDict);
acroForm.setDefaultResources(res);
document.getDocumentCatalog().setAcroForm(acroForm);
PDGamma colourBlack = new PDGamma();
PDAppearanceCharacteristicsDictionary fieldAppearance =
new PDAppearanceCharacteristicsDictionary(new COSDictionary());
fieldAppearance.setBorderColour(colourBlack);
if(ticked) {
COSArray arr = new COSArray();
arr.add(new COSFloat(0.89f));
arr.add(new COSFloat(0.937f));
arr.add(new COSFloat(1f));
fieldAppearance.setBackground(new PDGamma(arr));
}
COSDictionary cosDict = new COSDictionary();
COSArray rect = new COSArray();
rect.add(new COSFloat(x));
rect.add(new COSFloat(new Float(y-5)));
rect.add(new COSFloat(new Float(x+10)));
rect.add(new COSFloat(new Float(y+5)));
cosDict.setItem(COSName.RECT, rect);
cosDict.setItem(COSName.FT, COSName.getPDFName("Btn")); // Field Type
cosDict.setItem(COSName.TYPE, COSName.ANNOT);
cosDict.setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
if(ticked) {
cosDict.setItem(COSName.TU, new COSString("Checkbox with PDFBox"));
}
cosDict.setItem(COSName.T, new COSString("Chk"));
//Tick mark color and size of the mark
cosDict.setItem(COSName.DA, new COSString(ticked?"/F0 10 Tf 0 0.4 0 rg":"/FF 1 Tf 0 0 g"));
cosDict.setInt(COSName.F, 4);
PDCheckbox checkbox = new PDCheckbox(acroForm, cosDict);
checkbox.setFieldFlags(PDCheckbox.FLAG_READ_ONLY);
checkbox.setValue("Yes");
checkbox.getWidget().setAppearanceCharacteristics(fieldAppearance);
pdPage.getAnnotations().add(checkbox.getWidget());
acroForm.getFields().add(checkbox);
}
示例5: test
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="https://stackoverflow.com/questions/46642994/how-to-create-pdf-package-using-pdfbox">
* How to create pdf package using PdfBox?
* </a>
* <p>
* This test implements the equivalent of the OP's code turning
* a regular PDF into a portable collection.
* </p>
*/
@Test
public void test() throws IOException {
try ( InputStream resource = getClass().getResourceAsStream("/mkl/testarea/pdfbox2/sign/test.pdf"))
{
PDDocument pdDocument = PDDocument.load(resource);
COSDictionary collectionDictionary = new COSDictionary();
collectionDictionary.setName(COSName.TYPE, "Collection");
collectionDictionary.setName("View", "T");
PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
catalog.getCOSObject().setItem("Collection", collectionDictionary);
pdDocument.save(new File(RESULT_FOLDER, "test-collection.pdf"));
}
}
示例6: testReadFormOptions
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/36964496/pdfbox-2-0-overcoming-dictionary-key-encoding">
* PDFBox 2.0: Overcoming dictionary key encoding
* </a>
* <br/>
* <a href="http://www.stockholm.se/PageFiles/85478/KYF%20211%20Best%C3%A4llning%202014.pdf">
* KYF 211 Beställning 2014.pdf
* </a>
*
* <p>
* Indeed, the special characters in the names are replaced by the Unicode replacement
* character. PDFBox, when parsing a PDF name, immediately interprets its bytes as UTF-8
* encoded which fails in the document at hand.
* </p>
*/
@Test
public void testReadFormOptions() throws IOException
{
try ( InputStream originalStream = getClass().getResourceAsStream("KYF 211 Best\u00e4llning 2014.pdf") )
{
PDDocument pdfDocument = PDDocument.load(originalStream);
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
PDField field = acroForm.getField("Krematorier");
List<PDAnnotationWidget> widgets = field.getWidgets();
System.out.println("Field Name: " + field.getPartialName() + " (" + widgets.size() + ")");
for (PDAnnotationWidget annot : widgets) {
PDAppearanceDictionary ap = annot.getAppearance();
Set<COSName> keys = ((COSDictionary)(ap.getCOSObject().getDictionaryObject("N"))).keySet();
ArrayList<String> keyList = new ArrayList<>(keys.size());
for (COSName cosKey : keys) {keyList.add(cosKey.getName());}
System.out.println(String.join("|", keyList));
}
}
}
示例7: validate
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* Validates the PDF file specified in the constructor
* @return PDFDocumentInfo structure
**/
public PDFDocumentInfo validate() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
String infoString = null;
PDDocument document = null;
try {
document = PDDocument.load(new File(path));
COSDictionary trailer = document.getDocument().getTrailer();
COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM);
if (acroForm == null) {
return doc;
}
COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
for (int i = 0; i < fields.size(); i ++) {
COSDictionary field = (COSDictionary) fields.getObject(i);
COSName type = field.getCOSName(COSName.FT);
if (COSName.SIG.equals(type)) {
COSDictionary sig = (COSDictionary) field.getDictionaryObject(COSName.V);
if (sig != null) {
getSignatureInfo(sig);
}
}
}
}
finally {
if (document != null) {
document.close();
}
}
return doc;
}
示例8: addDssDictionary
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
@Override
public void addDssDictionary(InputStream inputStream, OutputStream outputStream, List<DSSDictionaryCallback> callbacks) {
PDDocument pdDocument = null;
try {
pdDocument = PDDocument.load(inputStream);
if (Utils.isCollectionNotEmpty(callbacks)) {
final COSDictionary cosDictionary = pdDocument.getDocumentCatalog().getCOSObject();
cosDictionary.setItem("DSS", buildDSSDictionary(callbacks));
cosDictionary.setNeedToBeUpdated(true);
}
pdDocument.saveIncremental(outputStream);
} catch (Exception e) {
throw new DSSException(e);
} finally {
Utils.closeQuietly(pdDocument);
}
}
示例9: process
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* process : BI : begin inline image.
*
* @param operator
* The operator that is being executed.
* @param arguments
* List
* @throws IOException
* If there is an error displaying the inline image.
*/
public void process(Operator operator, List<COSBase> arguments)
throws IOException {
Matrix ctm = context.getCurrentTransformationMatrix();
COSDictionary params = operator.getImageParameters();
int width = params.getInt(COSName.W, COSName.WIDTH, -1);
int height = params.getInt(COSName.H, COSName.HEIGHT, -1);
// TODO: use transform().
float minX = ctm.getTranslateX();
float maxX = minX + (width * ctm.getScaleX());
float minY = ctm.getTranslateY();
float maxY = minY + (height * ctm.getScaleY());
// Type3 streams may contain BI operands, but we don't wan't to consider
// those.
if (!context.isType3Stream()) {
// Rectangle boundBox = new SimpleRectangle(minX, minY, maxX, maxY);
Rectangle boundBox = SimpleRectangle.from2Vertices(
new SimplePoint(minX, minY),
new SimplePoint(maxX, maxY));
PDImage image = new PDInlineImage(operator.getImageParameters(),
operator.getImageData(), context.getResources());
PdfBoxColor exclusiveColor = getExclusiveColor(image.getImage());
if (exclusiveColor != null) {
PdfBoxShape shape = new PdfBoxShape(context.getCurrentPage());
shape.setRectangle(boundBox);
shape.setColor(exclusiveColor);
context.showShape(shape);
} else {
PdfBoxFigure figure = new PdfBoxFigure(context.getCurrentPage());
figure.setRectangle(boundBox);
context.showFigure(figure);
}
}
}
示例10: setField
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
public static void setField(PDDocument _pdfDocument, String name, String value) throws IOException
{
PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
PDField field = acroForm.getField(name);
COSDictionary dict = ((PDField) field).getDictionary();
COSString defaultAppearance = (COSString) dict
.getDictionaryObject(COSName.DA);
if (defaultAppearance != null)
{
dict.setString(COSName.DA, "/Helv 10 Tf 0 g");
if (name.equalsIgnoreCase("Field1")) {
dict.setString(COSName.DA, "/Helv 12 Tf 0 g");
}
}
if (field instanceof PDTextbox)
{
field = new PDTextbox(acroForm, dict);
((PDField) field).setValue(value);
}
}
示例11: setFieldBold
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
public static void setFieldBold(PDDocument _pdfDocument, String name, String value) throws IOException
{
PDDocumentCatalog docCatalog = _pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
PDField field = acroForm.getField(name);
COSDictionary dict = ((PDField) field).getDictionary();
COSString defaultAppearance = (COSString) dict
.getDictionaryObject(COSName.DA);
if (defaultAppearance != null)
{
dict.setString(COSName.DA, "/Helv 10 Tf 2 Tr .5 w 0 g");
if (name.equalsIgnoreCase("Field1")) {
dict.setString(COSName.DA, "/Helv 12 Tf 0 g");
}
}
if (field instanceof PDTextbox)
{
field = new PDTextbox(acroForm, dict);
((PDField) field).setValue(value);
}
}
示例12: test
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
void test(String resourceName, File resultFile) throws IOException, COSVisitorException, CertificateEncodingException
{
try ( InputStream source = getClass().getResourceAsStream(resourceName);
FileOutputStream fos = new FileOutputStream(resultFile);
FileInputStream fis = new FileInputStream(resultFile);
)
{
List<byte[]> certificates = new ArrayList<byte[]>();
for (int i = 0; i < cert.length; i++)
certificates.add(cert[i].getEncoded());
COSDictionary dss = createDssDictionary(certificates, null, null);
byte inputBytes[] = IOUtils.toByteArray(source);
PDDocument pdDocument = PDDocument.load(new ByteArrayInputStream(inputBytes));
PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
catalog.getCOSObject().setNeedToBeUpdate(true);
catalog.getCOSDictionary().setItem(COSName.getPDFName("DSS"), dss);
fos.write(inputBytes);
pdDocument.saveIncremental(fis, fos);
pdDocument.close();
}
}
示例13: testInsertPages
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/35964628/pdfbox-split-into-3-at-specified-page-numbers-to-insert-pdf">
* PDFBox Split into 3 at specified page numbers (to insert pdf)
* </a>
* <p>
* This test shows how to insert the same single page into another document multiple times.
* </p>
* <p>
* Beware, this code assumes a flat page tree. In case of deeper page trees one has to
* walk the page list differently, respect the count of contained {@link PDPageNode}
* objects and recurse if appropriate.
* </p>
*/
@Test
public void testInsertPages() throws IOException, COSVisitorException
{
PDDocument document = create100Pages();
PDDocument singlePageDocument = create1Page("A");
PDPage singlePage = (PDPage) singlePageDocument.getDocumentCatalog().getAllPages().get(0);
PDPageNode rootPages = document.getDocumentCatalog().getPages();
rootPages.getKids().add(3-1, singlePage);
singlePage.setParent(rootPages);
singlePage = new PDPage(new COSDictionary(singlePage.getCOSDictionary()));
rootPages.getKids().add(7-1, singlePage);
singlePage = new PDPage(new COSDictionary(singlePage.getCOSDictionary()));
rootPages.getKids().add(10-1, singlePage);
rootPages.updateCount();
document.save(new File(RESULT_FOLDER, "100-A-at-3.pdf"));
}
示例14: extractPatternImages
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
public void extractPatternImages(PDPatternResources pattern, String patternFormat) throws IOException
{
COSDictionary resourcesDict = (COSDictionary) pattern.getCOSDictionary().getDictionaryObject(COSName.RESOURCES);
if (resourcesDict == null)
return;
PDResources resources = new PDResources(resourcesDict);
Map<String, PDXObject> xObjects = resources.getXObjects();
if (xObjects == null)
return;
for (Map.Entry<String, PDXObject> entry : xObjects.entrySet())
{
PDXObject xObject = entry.getValue();
String xObjectFormat = String.format(patternFormat, "-" + entry.getKey() + "%s", "%s");
if (xObject instanceof PDXObjectForm)
extractPatternImages((PDXObjectForm)xObject, xObjectFormat);
else if (xObject instanceof PDXObjectImage)
extractPatternImages((PDXObjectImage)xObject, xObjectFormat);
}
}
示例15: prepareImageXObject
import org.apache.pdfbox.cos.COSDictionary; //导入依赖的package包/类
/**
* Create a PDImageXObject while making a decision whether not to
* compress, use Flate filter only, or Flate and LZW filters.
*
* @param document The document.
* @param byteArray array with data.
* @param width the image width
* @param height the image height
* @param bitsPerComponent the bits per component
* @param initColorSpace the color space
* @return the newly created PDImageXObject with the data compressed.
* @throws IOException
*/
private static PDImageXObject prepareImageXObject(PDDocument document,
byte [] byteArray, int width, int height, int bitsPerComponent,
PDColorSpace initColorSpace) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Filter filter = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE);
filter.encode(new ByteArrayInputStream(byteArray), baos, new COSDictionary(), 0);
ByteArrayInputStream encodedByteStream = new ByteArrayInputStream(baos.toByteArray());
return new PDImageXObject(document, encodedByteStream, COSName.FLATE_DECODE,
width, height, bitsPerComponent, initColorSpace);
}