List of usage examples for com.lowagie.text Image setDpi
public void setDpi(int dpiX, int dpiY)
From source file:de.cuseb.bilderbuch.pdf.PdfController.java
License:Open Source License
@RequestMapping(value = "/pdf", method = RequestMethod.GET) public void generatePdf(HttpSession session, HttpServletResponse httpServletResponse) { try {// www . j av a 2s. c om PdfRequest pdfRequest = (PdfRequest) session.getAttribute("pdfRequest"); httpServletResponse.setContentType("application/pdf"); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, httpServletResponse.getOutputStream()); writer.setDefaultColorspace(PdfName.COLORSPACE, PdfName.DEFAULTRGB); //document.addAuthor(pdfRequest.getAuthor()); //document.addTitle(pdfRequest.getTitle()); document.setPageSize( new Rectangle(Utilities.millimetersToPoints(156), Utilities.millimetersToPoints(148))); document.open(); FontFactory.defaultEmbedding = true; FontFactory.register("IndieRock.ttf", "IndieRock"); Font font = FontFactory.getFont("IndieRock"); BaseFont baseFont = font.getBaseFont(); PdfContentByte cb = writer.getDirectContent(); Iterator<PdfPage> pages = pdfRequest.getPages().iterator(); while (pages.hasNext()) { PdfPage page = pages.next(); if (page.getImage() != null) { Image image = Image.getInstance(new URL(page.getImage().getUrl())); image.setDpi(300, 300); image.setAbsolutePosition(0f, 0f); image.scaleAbsolute(document.getPageSize().getWidth(), document.getPageSize().getHeight()); document.add(image); cb.saveState(); cb.beginText(); cb.setColorFill(Color.WHITE); cb.moveText(10f, 10f); cb.setFontAndSize(baseFont, 18); cb.showText(page.getSentence()); cb.endText(); cb.restoreState(); if (pages.hasNext()) { document.newPage(); } } } document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java
License:Open Source License
private void handleGroup(PipelineContext pipelineContext, GroupContext groupContext, List<Element> statements, FunctionLibrary functionLibrary, PdfReader reader) throws DocumentException, IOException { final NodeInfo contextNode = (NodeInfo) groupContext.contextNodeSet.get(groupContext.contextPosition - 1); final Map<String, ValueRepresentation> variableToValueMap = new HashMap<String, ValueRepresentation>(); variableToValueMap.put("page-count", new Int64Value(reader.getNumberOfPages())); variableToValueMap.put("page-number", new Int64Value(groupContext.pageNumber)); variableToValueMap.put("page-height", new FloatValue(groupContext.pageHeight)); // Iterate through statements for (final Element currentElement : statements) { // Check whether this statement applies to the current page final String elementPage = currentElement.attributeValue("page"); if ((elementPage != null) && !Integer.toString(groupContext.pageNumber).equals(elementPage)) continue; final NamespaceMapping namespaceMapping = new NamespaceMapping( Dom4jUtils.getNamespaceContextNoDefault(currentElement)); final String elementName = currentElement.getName(); if (elementName.equals("group")) { // Handle group final GroupContext newGroupContext = new GroupContext(groupContext); final String ref = currentElement.attributeValue("ref"); if (ref != null) { final NodeInfo newContextNode = (NodeInfo) XPathCache.evaluateSingle( groupContext.contextNodeSet, groupContext.contextPosition, ref, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); if (newContextNode == null) continue; newGroupContext.contextNodeSet = Collections.singletonList((Item) newContextNode); newGroupContext.contextPosition = 1; }/*from w w w .j a v a2s . c o m*/ final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x")); if (offsetXString != null) { newGroupContext.offsetX = groupContext.offsetX + Float.parseFloat(offsetXString); } final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y")); if (offsetYString != null) { newGroupContext.offsetY = groupContext.offsetY + Float.parseFloat(offsetYString); } final String fontPitch = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-pitch")); if (fontPitch != null) newGroupContext.fontPitch = Float.parseFloat(fontPitch); final String fontFamily = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-family")); if (fontFamily != null) newGroupContext.fontFamily = fontFamily; final String fontSize = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-size")); if (fontSize != null) newGroupContext.fontSize = Float.parseFloat(fontSize); handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary, reader); } else if (elementName.equals("repeat")) { // Handle repeat final String nodeset = currentElement.attributeValue("nodeset"); final List iterations = XPathCache.evaluate(groupContext.contextNodeSet, groupContext.contextPosition, nodeset, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x")); final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y")); final float offsetIncrementX = (offsetXString == null) ? 0 : Float.parseFloat(offsetXString); final float offsetIncrementY = (offsetYString == null) ? 0 : Float.parseFloat(offsetYString); for (int iterationIndex = 1; iterationIndex <= iterations.size(); iterationIndex++) { final GroupContext newGroupContext = new GroupContext(groupContext); newGroupContext.contextNodeSet = iterations; newGroupContext.contextPosition = iterationIndex; newGroupContext.offsetX = groupContext.offsetX + (iterationIndex - 1) * offsetIncrementX; newGroupContext.offsetY = groupContext.offsetY + (iterationIndex - 1) * offsetIncrementY; handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary, reader); } } else if (elementName.equals("field")) { final String fieldNameStr = currentElement.attributeValue("acro-field-name"); if (fieldNameStr != null) { final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); // Get value from instance final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); groupContext.acroFields.setField(fieldName, text); } else { // Handle field final String leftAttribute = currentElement.attributeValue("left") == null ? currentElement.attributeValue("left-position") : currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top") == null ? currentElement.attributeValue("top-position") : currentElement.attributeValue("top"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size")); final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext, groupContext, variableToValueMap, contextNode); // Output value final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); groupContext.contentByte.beginText(); { groupContext.contentByte.setFontAndSize(baseFont, fontAttributes.fontSize); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); // Get value from instance final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); // Iterate over characters and print them if (text != null) { int len = Math.min(text.length(), (size != null) ? Integer.parseInt(size) : Integer.MAX_VALUE); for (int j = 0; j < len; j++) groupContext.contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, text.substring(j, j + 1), xPosition + ((float) j) * fontAttributes.fontPitch, yPosition, 0); } } groupContext.contentByte.endText(); } } else if (elementName.equals("barcode")) { // Handle barcode final String leftAttribute = currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); // final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size")); final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); final String type = currentElement.attributeValue("type") == null ? "CODE39" : currentElement.attributeValue("type"); final float height = currentElement.attributeValue("height") == null ? 10.0f : Float.parseFloat(currentElement.attributeValue("height")); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext, groupContext, variableToValueMap, contextNode); final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); final Barcode barcode = createBarCode(type); barcode.setCode(text); barcode.setBarHeight(height); barcode.setFont(baseFont); barcode.setSize(fontAttributes.fontSize); final Image barcodeImage = barcode.createImageWithBarcode(groupContext.contentByte, null, null); barcodeImage.setAbsolutePosition(xPosition, yPosition); groupContext.contentByte.addImage(barcodeImage); } else if (elementName.equals("image")) { // Handle image // Read image final Image image; { final String hrefAttribute = currentElement.attributeValue("href"); final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(hrefAttribute); if (inputName != null) { // Read the input final ByteArrayOutputStream os = new ByteArrayOutputStream(); readInputAsSAX(pipelineContext, inputName, new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false)); // Create the image image = Image.getInstance(os.toByteArray()); } else { // Read and create the image final URL url = URLFactory.createURL(hrefAttribute); // Use ConnectionResult so that header/session forwarding takes place final ConnectionResult connectionResult = new Connection().open( NetUtils.getExternalContext(), new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), url, null, null, null, null, Connection.getForwardHeaders()); if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException("Got invalid return code while loading image: " + url.toExternalForm() + ", " + connectionResult.statusCode); } // Make sure things are cleaned-up not too late pipelineContext.addContextListener(new PipelineContext.ContextListener() { public void contextDestroyed(boolean success) { connectionResult.close(); } }); // Here we decide to copy to temp file and load as a URL. We could also provide bytes directly. final String tempURLString = NetUtils.inputStreamToAnyURI( connectionResult.getResponseInputStream(), NetUtils.REQUEST_SCOPE); image = Image.getInstance(URLFactory.createURL(tempURLString)); } } final String fieldNameStr = currentElement.attributeValue("acro-field-name"); if (fieldNameStr != null) { // Use field as placeholder final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final float[] positions = groupContext.acroFields.getFieldPositions(fieldName); if (positions != null) { final Rectangle rectangle = new Rectangle(positions[1], positions[2], positions[3], positions[4]); // This scales the image so that it fits in the box (but the aspect ratio is not changed) image.scaleToFit(rectangle.getWidth(), rectangle.getHeight()); final float yPosition = positions[2] + rectangle.getHeight() - image.getScaledHeight(); image.setAbsolutePosition( positions[1] + (rectangle.getWidth() - image.getScaledWidth()) / 2, yPosition); // Add image groupContext.contentByte.addImage(image); } } else { // Use position, etc. final String leftAttribute = currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top"); final String scalePercentAttribute = currentElement.attributeValue("scale-percent"); final String dpiAttribute = currentElement.attributeValue("dpi"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); final String scalePercent = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, scalePercentAttribute); final String dpi = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, dpiAttribute); // Set image parameters image.setAbsolutePosition(xPosition, yPosition); if (scalePercent != null) { image.scalePercent(Float.parseFloat(scalePercent)); } if (dpi != null) { final int dpiInt = Integer.parseInt(dpi); image.setDpi(dpiInt, dpiInt); } // Add image groupContext.contentByte.addImage(image); } } else { // NOP } } }