本文整理汇总了Java中org.apache.pdfbox.cos.COSName类的典型用法代码示例。如果您正苦于以下问题:Java COSName类的具体用法?Java COSName怎么用?Java COSName使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
COSName类属于org.apache.pdfbox.cos包,在下文中一共展示了COSName类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: removeText
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
private PDDocument removeText(PDPage page) throws IOException {
PDFStreamParser parser = new PDFStreamParser(page);
parser.parse();
List<Object> tokens = parser.getTokens();
List<Object> newTokens = new ArrayList<>();
for (Object token : tokens) {
if (token instanceof Operator) {
Operator op = (Operator) token;
if (op.getName().equals("TJ") || op.getName().equals("Tj")) {
//remove the one argument to this operator
newTokens.remove(newTokens.size() - 1);
continue;
}
}
newTokens.add(token);
}
PDDocument document = new PDDocument();
document.addPage(page);
PDStream newContents = new PDStream(document);
OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE);
ContentStreamWriter writer = new ContentStreamWriter(out);
writer.writeTokens(newTokens);
out.close();
page.setContents(newContents);
return document;
}
示例2: testRenderSdnList
import org.apache.pdfbox.cos.COSName; //导入依赖的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();
}
}
}
}
示例3: testRemoveLikeStephanImproved
import org.apache.pdfbox.cos.COSName; //导入依赖的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"));
}
}
示例4: testRender4700198773
import org.apache.pdfbox.cos.COSName; //导入依赖的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();
}
}
}
}
示例5: findPhoto
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
public static void findPhoto(String path,int empId) throws IOException, SQLException, Error{
// Loading an existing document
int imageFound=0;
File file = new File(path);
PDDocument document=PDDocument.load(file);
PDPageTree list=document.getPages();
for(PDPage page:list){ //check in all pages of pdf
PDResources pdResources=page.getResources(); //get all resources
for(COSName cosName:pdResources.getXObjectNames()) //loop for all resources
{
PDXObject pdxObject=pdResources.getXObject(cosName);
if (pdxObject instanceof PDImageXObject) { //check that the resource is image
BufferedImage br=((PDImageXObject) pdxObject).getImage();
RgbImage im = RgbImageJ2se.toRgbImage(br);
// step #3 - convert image to greyscale 8-bits
RgbAvgGray toGray = new RgbAvgGray();
toGray.push(im);
// step #4 - initialize face detector with correct Haar profile
InputStream is = ExtractPhoto.class.getResourceAsStream("/haar/HCSB.txt");
Gray8DetectHaarMultiScale detectHaar = new Gray8DetectHaarMultiScale(is, 1,40);
// step #5 - apply face detector to grayscale image
List<Rect> result= detectHaar.pushAndReturn(toGray.getFront());
if(result.size()!=0)
{
database.StorePhoto.storePhoto(empId,br);
imageFound=1;
break;
}
}
}
if(imageFound==1)
break;
}
System.out.println(imageFound);
if(imageFound!=1){
BufferedImage in = ImageIO.read(ExtractPhoto.class.getResource("/images/nopic.jpg"));
database.StorePhoto.storePhoto(empId,in);
}
document.close();
}
示例6: build
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
public byte[] build() throws IOException {
this.acroForm.setNeedAppearances(false);
// Fix annotations
for (PDPage page : this.pdfDocument.getPages()) {
for (PDAnnotation annot : page.getAnnotations()) {
annot.setPage(page);
}
}
// Define font resources names used in PDF template
final PDResources dr = new PDResources();
dr.put(COSName.getPDFName("Helv"), PDType1Font.HELVETICA);
dr.put(COSName.getPDFName("HeBo"), PDType1Font.HELVETICA_BOLD);
this.acroForm.setDefaultResources(dr);
// Convert form fields to text
this.acroForm.flatten();
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
pdfDocument.save(bos);
pdfDocument.close();
return bos.toByteArray();
}
示例7: getImagesFromResources
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
private List<RenderedImage> getImagesFromResources(PDResources resources) throws IOException {
List<RenderedImage> images = new ArrayList<>();
for (COSName xObjectName : resources.getXObjectNames()) {
PDXObject xObject = resources.getXObject(xObjectName);
if (xObject instanceof PDImageXObject) {
images.add(((PDImageXObject) xObject).getImage());
} else if (xObject instanceof PDFormXObject) {
images.addAll(getImagesFromResources(((PDFormXObject) xObject).getResources()));
}
}
return images;
}
示例8: process
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
@Override
public void process(Operator operator, List<COSBase> arguments)
throws IOException {
// set parameters from graphics state parameter dictionary
COSName dictName = (COSName) arguments.get(0);
PDExtendedGraphicsState gs = context.getResources().getExtGState(dictName);
gs.copyIntoGraphicsState(context.getGraphicsState());
}
示例9: process
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
@Override
public void process(Operator operator, List<COSBase> arguments)
throws IOException {
PDColorSpace cs = context.getResources().getColorSpace(COSName.DEVICERGB);
context.getGraphicsState().setNonStrokingColorSpace(cs);
super.process(operator, arguments);
}
示例10: writeInputFieldToPDFPage
import org.apache.pdfbox.cos.COSName; //导入依赖的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);
}
示例11: PdfBoxGraphics2D
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
/**
* @param document
* The document the graphics should be used to create a XForm in.
* @param bbox
* Bounding Box of the graphics
* @throws IOException
* when something goes wrong with writing into the content
* stream of the {@link PDDocument}.
*/
public PdfBoxGraphics2D(PDDocument document, PDRectangle bbox) throws IOException {
this.document = document;
this.bbox = bbox;
PDAppearanceStream appearance = new PDAppearanceStream(document);
xFormObject = appearance;
xFormObject.setResources(new PDResources());
xFormObject.setBBox(bbox);
contentStream = new PDPageContentStream(document, appearance, xFormObject.getStream().createOutputStream(COSName.FLATE_DECODE));
contentStreamSaveState();
baseTransform = new AffineTransform();
baseTransform.translate(0, bbox.getHeight());
baseTransform.scale(1, -1);
calcImage = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);
calcGfx = calcImage.createGraphics();
font = calcGfx.getFont();
cloneInfo = null;
}
示例12: PdfImageCounter
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
public PdfImageCounter() {
addOperator(new OperatorProcessor() {
@Override
public void process(Operator operator, List<COSBase> arguments) throws IOException {
if (arguments.size() < 1) {
throw new org.apache.pdfbox.contentstream.operator.MissingOperandException(operator, arguments);
}
if (isImage(arguments.get(0))) {
documentImageCount++;
}
}
protected Boolean isImage(COSBase base) {
return (base instanceof COSName) &&
context.getResources().isImageXObject((COSName)base);
}
@Override
public String getName() {
return "Do";
}
});
}
示例13: drawString
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
private static void drawString(PDPageContentStream contentStream, String text) throws IOException {
if (contentStream != null && text != null && text.length() > 0) {
char[] tc = text.toCharArray();
StringBuilder sb = new StringBuilder();
Encoding encoding = EncodingManager.INSTANCE.getEncoding(COSName.WIN_ANSI_ENCODING);
for (int i = 0; i < tc.length; i++) {
Character c = tc[i];
try {
sb.appendCodePoint(encoding.getCode(encoding.getNameFromCharacter(c)));
} catch (IOException e) {
sb.append(c);
}
}
contentStream.drawString(sb.toString());
}
}
示例14: buildImgKeyToPolNameMapping
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
private static void buildImgKeyToPolNameMapping(PDPage page) throws IOException {
PDStream contents = page.getContents();
PDFStreamParser parser = new PDFStreamParser(contents.getStream());
parser.parse();
List tokens = parser.getTokens();
boolean concatStringPhase = false;
String polName = "";
String lastText = "";
for (int index = 0; index < tokens.size(); index++) {
Object obj = tokens.get(index);
if (obj instanceof PDFOperator) {
PDFOperator op = (PDFOperator) obj;
if (op.getOperation().equals("BT")) {
concatStringPhase = true;
polName = lastText;
lastText = "";
}
else if (op.getOperation().equals("ET")) {
concatStringPhase = false;
}
}
else if (concatStringPhase && obj instanceof COSString) {
COSString cosString = (COSString) obj;
lastText += " " + cosString.getString();
lastText = lastText.trim();
}
else if (!concatStringPhase && obj instanceof COSName) {
COSName cosName = (COSName) obj;
if (cosName.getName().startsWith("img")) {
mapImgKeyToPolName.put(cosName.getName(), polName);
}
}
}
}
示例15: extractFontResources
import org.apache.pdfbox.cos.COSName; //导入依赖的package包/类
private void extractFontResources(PDResources resources) throws IOException {
for (COSName key : resources.getFontNames()) {
PDFont font = resources.getFont(key);
extractStrategy.extract(font);
}
for (COSName name : resources.getXObjectNames()) {
PDXObject xobject = resources.getXObject(name);
if (xobject instanceof PDFormXObject) {
PDFormXObject xObjectForm = (PDFormXObject) xobject;
PDResources formResources = xObjectForm.getResources();
if (formResources != null)
extractFontResources(formResources);
}
}
}