当前位置: 首页>>代码示例>>Java>>正文


Java COSName类代码示例

本文整理汇总了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;

    }
 
开发者ID:redmyers,项目名称:484_P7_1-Java,代码行数:32,代码来源:NurminenDetectionAlgorithm.java

示例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();
            }
        }
    }
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox2,代码行数:71,代码来源:RenderType3Character.java

示例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"));
    }
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox2,代码行数:52,代码来源:RemoveStrikeoutComment.java

示例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();
            }
        }
    }
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox2,代码行数:71,代码来源:RenderType3Character.java

示例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();	
	}
 
开发者ID:djdivix,项目名称:IDBuilderFX,代码行数:41,代码来源:ExtractPhoto.java

示例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();
}
 
开发者ID:suomenriistakeskus,项目名称:oma-riista-web,代码行数:25,代码来源:HunterPaymentPdfFeature.java

示例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;
    }
 
开发者ID:abelsromero,项目名称:pdf-box-examples,代码行数:14,代码来源:PdfImagesHelper.java

示例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());
}
 
开发者ID:ckorzen,项目名称:icecite,代码行数:9,代码来源:SetGraphicsStateParameters.java

示例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);
}
 
开发者ID:ckorzen,项目名称:icecite,代码行数:8,代码来源:SetNonStrokingDeviceRGBColor.java

示例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);
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox1,代码行数:66,代码来源:CreateCheckbox.java

示例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;
}
 
开发者ID:rototor,项目名称:pdfbox-graphics2d,代码行数:30,代码来源:PdfBoxGraphics2D.java

示例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";
        }
    });
}
 
开发者ID:hrbrmstr,项目名称:pdfbox,代码行数:24,代码来源:PdfImageCounter.java

示例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());
	}
}
 
开发者ID:phoenixctms,项目名称:ctsms,代码行数:17,代码来源:PDFUtil.java

示例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);
            }
        }
    }
}
 
开发者ID:TekkLabs,项目名称:memoria-politica,代码行数:38,代码来源:FedDepPhotosUtility.java

示例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);
        }
    }
}
 
开发者ID:m-abboud,项目名称:FontVerter,代码行数:18,代码来源:PdfFontExtractor.java


注:本文中的org.apache.pdfbox.cos.COSName类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。