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


Java COSString类代码示例

本文整理汇总了Java中org.apache.pdfbox.cos.COSString的典型用法代码示例。如果您正苦于以下问题:Java COSString类的具体用法?Java COSString怎么用?Java COSString使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


COSString类属于org.apache.pdfbox.cos包,在下文中一共展示了COSString类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: writeInputFieldToPDFPage

import org.apache.pdfbox.cos.COSString; //导入依赖的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

示例2: buildImgKeyToPolNameMapping

import org.apache.pdfbox.cos.COSString; //导入依赖的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

示例3: process

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
@Override
public void process(Operator operator, List<COSBase> arguments)
  throws IOException {
  if (arguments.isEmpty()) {
    throw new MissingOperandException(operator, arguments);
  }
      
  PDTextState textState = context.getGraphicsState().getTextState();
  float fontSize = textState.getFontSize();
  float horizontalScaling = textState.getHorizontalScaling() / 100f;
  boolean isVertical = textState.getFont().isVertical();

  COSArray array = (COSArray) arguments.get(0);
  for (COSBase obj : array) {
    if (obj instanceof COSNumber) {
      float tj = ((COSNumber) obj).floatValue();

      // calculate the combined displacements
      float tx, ty;
      if (isVertical) {
        tx = 0;
        ty = -tj / 1000 * fontSize;
      } else {
        tx = -tj / 1000 * fontSize * horizontalScaling;
        ty = 0;
      }

      Matrix translate = Matrix.getTranslateInstance(tx, ty);
      context.getTextMatrix().concatenate(translate);
    } else if (obj instanceof COSString) {
      List<COSBase> args = new ArrayList<COSBase>();
      args.add(obj);
      context.processOperator("Tj", args);
    } else {
      throw new IOException("Unknown type in array for TJ operation:" + obj);
    }
  }
}
 
开发者ID:ckorzen,项目名称:icecite,代码行数:39,代码来源:ShowTextWithIndividualGlyphPositioning.java

示例4: setField

import org.apache.pdfbox.cos.COSString; //导入依赖的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);
	}
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox1,代码行数:23,代码来源:FillFormCustomFont.java

示例5: setFieldBold

import org.apache.pdfbox.cos.COSString; //导入依赖的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);
	}
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox1,代码行数:23,代码来源:FillFormCustomFont.java

示例6: process

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
/**
     * TJ Show text, allowing individual glyph positioning.
     * @param operator The operator that is being executed.
     * @param arguments List
     * @throws IOException If there is an error processing this operator.
     */
    public void process(PDFOperator operator, List arguments) throws IOException 
    {
    	((PDFObjectExtractor)context).setNewTextFragment(true);
        COSArray array = (COSArray)arguments.get( 0 );
        float adjustment=0;
        for( int i=0; i<array.size(); i++ )
        {
            COSBase next = array.get( i );
            if( next instanceof COSNumber )
            {
                adjustment = ((COSNumber)next).floatValue();

                Matrix adjMatrix = new Matrix();
                adjustment=(-adjustment/1000)*context.getGraphicsState().getTextState().getFontSize() *
                    (context.getGraphicsState().getTextState().getHorizontalScalingPercent()/100);
                adjMatrix.setValue( 2, 0, adjustment );
                context.setTextMatrix( adjMatrix.multiply( context.getTextMatrix() ) );
            }
            else if( next instanceof COSString )
            {
//            	TEST 27.08.09
//            	((PDFObjectExtractor)context).setNewTextFragment(true);
            	
            	((PDFObjectExtractor)context).showString( ((COSString)next).getBytes() , i);
                //((PDFObjectExtractor)context).setNewTextFragment(false);
                // automatically set in addCharacter method (simplest way possible)
            }
            else
            {
                throw new IOException( "Unknown type in array for TJ operation:" + next );
            }
        }
    }
 
开发者ID:tamirhassan,项目名称:pdfxtk,代码行数:40,代码来源:ShowTextGlyph.java

示例7: get

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
@Override
public byte[] get(String name) throws IOException {
	COSBase val = wrapped.getDictionaryObject(name);
	if (val == null) {
		return null;
	}
	if (val instanceof COSString) {
		return ((COSString) val).getBytes();
	}
	if (val instanceof COSName) {
		return ((COSName) val).getName().getBytes();
	}
	throw new IOException(name + " was expected to be a COSString element but was " + val.getClass() + " : " + val);
}
 
开发者ID:esig,项目名称:dss,代码行数:15,代码来源:PdfBoxDict.java

示例8: testDrunkenfistOriginal

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
/**
 * <a href="http://stackoverflow.com/questions/29220165/editing-content-in-pdf-using-pdfbox-removes-last-line-from-pdf">
 * Editing content in pdf using PDFBox removes last line from pdf
 * </a>
 * 
 * Reproducing the issue.
 */
@Test
public void testDrunkenfistOriginal() throws IOException, COSVisitorException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("Original.pdf") )
    {
        PDDocument doc = PDDocument.load(originalStream);
        PDPage page = (PDPage) doc.getDocumentCatalog().getAllPages().get(0);
        PDStream contents = page.getContents();
        PDFStreamParser parser = new PDFStreamParser(contents.getStream());
        parser.parse();
        List<Object> tokens = parser.getTokens();
        for (int j = 0; j < tokens.size(); j++) {
            Object next = tokens.get(j);
            if (next instanceof PDFOperator) {
                PDFOperator op = (PDFOperator) next;
                if (op.getOperation().equals("Tj")) {
                    COSString previous = (COSString) tokens.get(j - 1);
                    String string = previous.getString();

                    string = string.replace("@ordnum&", "-ORDERNR-");
                    string = string.replace("@shipid&", "-SHIPMENTID-");
                    string = string.replace("@customer&", "-CUSTOMERNR-");
                    string = string.replace("@fromname&", "-FROMNAME-");

                    tokens.set(j - 1, new COSString(string.trim()));
                }
            }
        }

        PDStream updatedStream = new PDStream(doc);  
        OutputStream out = updatedStream.createOutputStream();  
        ContentStreamWriter tokenWriter = new ContentStreamWriter(out);  
        tokenWriter.writeTokens(tokens);  
        page.setContents(updatedStream);
        
        doc.save(new File(RESULT_FOLDER, "Original-edited.pdf"));
        doc.close();
    }
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox1,代码行数:47,代码来源:NaiveContentEdit.java

示例9: addMetadata

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
/**
 * Used when processing custom metadata entries, as PDFBox won't do the
 * conversion for us in the way it does for the standard ones
 */
private void addMetadata(Metadata metadata, String name, COSBase value) {
  if (value instanceof COSArray) {
    for (Object v : ((COSArray) value).toList()) {
      addMetadata(metadata, name, ((COSBase) v));
    }
  } else if (value instanceof COSString) {
    addMetadata(metadata, name, ((COSString) value).getString());
  } else if (value != null) {
    addMetadata(metadata, name, value.toString());
  }
}
 
开发者ID:kolbasa,项目名称:OCRaptor,代码行数:16,代码来源:PDFParser.java

示例10: stringValue

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
/**
 * Obtains a string from a PDF value
 * @param value the PDF value of the String, Integer or Float type
 * @return the corresponging string value
 */
protected String stringValue(COSBase value)
{
    if (value instanceof COSString)
        return ((COSString) value).getString();
    else if (value instanceof COSNumber)
        return String.valueOf(((COSNumber) value).floatValue());
    else
        return "";
}
 
开发者ID:radkovo,项目名称:Pdf2Dom,代码行数:15,代码来源:PDFBoxTree.java

示例11: getSignatures

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
private List<PdfSignatureOrDocTimestampInfo> getSignatures(CertificatePool validationCertPool, byte[] originalBytes) {
	List<PdfSignatureOrDocTimestampInfo> signatures = new ArrayList<PdfSignatureOrDocTimestampInfo>();
	PDDocument doc = null;
	try {
		doc = PDDocument.load(originalBytes);

		List<PDSignature> pdSignatures = doc.getSignatureDictionaries();
		if (Utils.isCollectionNotEmpty(pdSignatures)) {
			LOG.debug("{} signature(s) found", pdSignatures.size());

			PdfDict catalog = new PdfBoxDict(doc.getDocumentCatalog().getCOSObject(), doc);
			PdfDssDict dssDictionary = PdfDssDict.extract(catalog);

			for (PDSignature signature : pdSignatures) {
				String subFilter = signature.getSubFilter();

				COSDictionary dict = signature.getCOSObject();
				COSString item = (COSString) dict.getDictionaryObject(COSName.CONTENTS);
				byte[] cms = item.getBytes();

				byte[] cmsWithByteRange = signature.getContents(originalBytes);

				if (!Arrays.equals(cmsWithByteRange, cms)) {
					LOG.warn("The byte range doesn't match found /Content value!");
				}

				if (Utils.isStringEmpty(subFilter) || Utils.isArrayEmpty(cms)) {
					LOG.warn("Wrong signature with empty subfilter or cms.");
					continue;
				}

				byte[] signedContent = signature.getSignedContent(originalBytes);
				int[] byteRange = signature.getByteRange();

				PdfDict signatureDictionary = new PdfBoxDict(signature.getCOSObject(), doc);
				PdfSignatureOrDocTimestampInfo signatureInfo = null;
				if (PdfBoxDocTimeStampService.SUB_FILTER_ETSI_RFC3161.getName().equals(subFilter)) {
					boolean isArchiveTimestamp = false;

					// LT or LTA
					if (dssDictionary != null) {
						// check is DSS dictionary already exist
						if (isDSSDictionaryPresentInPreviousRevision(getOriginalBytes(byteRange, signedContent))) {
							isArchiveTimestamp = true;
						}
					}

					signatureInfo = new PdfBoxDocTimestampInfo(validationCertPool, signature, signatureDictionary, dssDictionary, cms, signedContent,
							isArchiveTimestamp);
				} else {
					signatureInfo = new PdfBoxSignatureInfo(validationCertPool, signature, signatureDictionary, dssDictionary, cms, signedContent);
				}

				if (signatureInfo != null) {
					signatures.add(signatureInfo);
				}
			}
			Collections.sort(signatures, new PdfSignatureOrDocTimestampInfoComparator());
			linkSignatures(signatures);

			for (PdfSignatureOrDocTimestampInfo sig : signatures) {
				LOG.debug("Signature " + sig.uniqueId() + " found with byteRange " + Arrays.toString(sig.getSignatureByteRange()) + " ("
						+ sig.getSubFilter() + ")");
			}
		}

	} catch (Exception e) {
		LOG.warn("Cannot analyze signatures : " + e.getMessage(), e);
	} finally {
		Utils.closeQuietly(doc);
	}

	return signatures;
}
 
开发者ID:esig,项目名称:dss,代码行数:75,代码来源:PdfBoxSignatureService.java

示例12: generateSimpleTemplate

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
/**
 * Generates a sample PDF template with one form field with the name "SampleField"
 */
byte[] generateSimpleTemplate() throws IOException, COSVisitorException
{
    try (   PDDocument template = new PDDocument();
            InputStream fontStream = getClass().getResourceAsStream("LiberationSans-Regular.ttf");
            ByteArrayOutputStream resultStream = new ByteArrayOutputStream()    )
    {
        PDPage page = new PDPage();
        template.addPage(page);
        
        PDTrueTypeFont font = PDTrueTypeFont.loadTTF(template, fontStream);
        
        // add a new AcroForm and add that to the document
        PDAcroForm acroForm = new PDAcroForm(template);
        template.getDocumentCatalog().setAcroForm(acroForm);
        
        // Add and set the resources and default appearance
        PDResources res = new PDResources();
        String fontName = res.addFont(font);
        acroForm.setDefaultResources(res);
        String da = "/" + fontName + " 12 Tf 0 g";
        //acroForm.setDefaultAppearance(da);

        COSDictionary cosDict = new COSDictionary();

        COSArray rect = new COSArray();
        rect.add(new COSFloat(250f)); // lower x boundary
        rect.add(new COSFloat(700f)); // lower y boundary
        rect.add(new COSFloat(500f)); // upper x boundary
        rect.add(new COSFloat(750f)); // upper y boundary

        cosDict.setItem(COSName.RECT, rect);
        cosDict.setItem(COSName.FT, COSName.getPDFName("Tx")); // Field Type
        cosDict.setItem(COSName.TYPE, COSName.ANNOT);
        cosDict.setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
        cosDict.setItem(COSName.DA, new COSString(da));

        // add a form field to the form
        PDTextbox textBox = new PDTextbox(acroForm, cosDict);
        textBox.setPartialName("SampleField");
        acroForm.getFields().add(textBox);
        
        // specify the annotation associated with the field
        // and add it to the page
        PDAnnotationWidget widget = textBox.getWidget();
        page.getAnnotations().add(widget);
        
        //textBox.setValue("Test");
        
        template.save(resultStream);
        return resultStream.toByteArray();
    }
    
    
}
 
开发者ID:mkl-public,项目名称:testarea-pdfbox1,代码行数:58,代码来源:AppendFormTwice.java

示例13: test

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
public void test() {
	

		String filePath = "";
		PDDocument document;
		try {
			document = PDDocument.load(new File(filePath));
					List<SignatureInformations> result = null;
		List<SignatureInformations> results = new ArrayList<SignatureInformations>();

		for (PDSignature sig : document.getSignatureDictionaries()) {
				COSDictionary sigDict = sig.getCOSObject();
				COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);
				FileInputStream fis = new FileInputStream(filePath);
				byte[] buf = null;

				try {
					buf = sig.getSignedContent(fis);
				} finally {
					fis.close();
				}

				CAdESChecker checker = new CAdESChecker();
				result = checker.checkDetattachedSignature(buf, contents.getBytes());
				if (result == null || result.isEmpty()) {
					//Erro
				}
				results.addAll(checker.getSignaturesInfo());
			}
		for (SignatureInformations sis : results){
			for (BasicCertificate bc : sis.getSignersBasicCertificates()){
				if (bc.hasCertificatePF()){
					System.out.println(bc.getICPBRCertificatePF().getCPF());
				}
				if (bc.hasCertificatePJ()){
					System.out.println(bc.getICPBRCertificatePJ().getCNPJ());
					System.out.println(bc.getICPBRCertificatePJ().getResponsibleCPF());
				}
				 
			}
		}			
		
	} catch (IOException e) {	
		e.printStackTrace();
	}
}
 
开发者ID:demoiselle,项目名称:signer,代码行数:47,代码来源:PDFVerify.java

示例14: process

import org.apache.pdfbox.cos.COSString; //导入依赖的package包/类
/**
 * Tj show Show text.
 * @param operator The operator that is being executed.
 * @param arguments List
 *
 * @throws IOException If there is an error processing this operator.
 */
public void process(PDFOperator operator, List arguments) throws IOException
{
	((PDFObjectExtractor)context).setNewTextFragment(true);
    COSString string = (COSString)arguments.get( 0 );
    ((PDFObjectExtractor)context).showString( string.getBytes() , -1);
}
 
开发者ID:tamirhassan,项目名称:pdfxtk,代码行数:14,代码来源:ShowText.java


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