pdfbox-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Philippe de Rochambeau <phi...@free.fr>
Subject Re: Rotate text
Date Sun, 26 Apr 2015 11:11:42 GMT
Here’s code that works: after the page has been rotated by 90 degrees, the field’s contents
appear vertical, as expected.

There’s a glitch, though:

templateAcroForm.getField("field0")

returns null

which is why I use

final PDField templateField0 = templatePdfFields.get(0);

instead, to retrieve the field from the form.

I am not sure why the field is null in the first case.

Philippe


————————————

public class App {

	final static File TEMPLATE_FOLDER = new File("/Users/philippe/templates");
	final static File RESULT_FOLDER = new File("/Users/philippe/results");
	
    public static void main( String[] args ) {
    		new App();
    }
    
    public App() {
    		try {
    			testGeneratedTemplate();
			} catch (COSVisitorException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
    }


——————————————————

 public void testGeneratedTemplate() throws COSVisitorException, IOException {
        
	  final byte[] generatedTemplate = generateSimpleTemplate();
	  final PDDocument templateDoc = new PDDocument().load(new ByteArrayInputStream(generatedTemplate));
	  Files.write(new File(TEMPLATE_FOLDER,  "template.pdf").toPath(), generatedTemplate);
	  
        final PDDocument finalDoc = new PDDocument();
        final List<PDField> fields = new ArrayList<PDField>();
        final int numberOfPages = 2;
        final float inch = 72;
        final float borderThickness = inch / 48f;
        final float distanceFromField = inch / 2f;
        
        for (int i = 0; i < numberOfPages; ++i) {
        		final PDDocumentCatalog templateDocCatalog = templateDoc.getDocumentCatalog();
          	final PDAcroForm templateAcroForm = templateDocCatalog.getAcroForm();

            //final PDField templateField0 = templateAcroForm.getField("field0");
          	final PDField templateField0 = templatePdfFields.get(0);
            if (templateField0 != null) {
	        		templateField0.setValue("xxx" + i);
	        		templateField0.setPartialName("field0-" + i);
	        		templateField0.setReadonly(true);
	        		 final List<PDPage> pages = (List<PDPage>) templateDocCatalog.getAllPages();
	        		 PDPage page = pages.get(0);
	        		 finalDoc.addPage(page);  
	              fields.add(templateField0);
            }
        }

        final PDAcroForm finalForm = new PDAcroForm(finalDoc);
        finalDoc.getDocumentCatalog().setAcroForm(finalForm);
        finalForm.setFields(fields);      
        
        finalDoc.save(new File(RESULT_FOLDER, "form-two-templates.pdf"));
        templateDoc.close();
        
       finalDoc.close();
        
        
    }

——————————————————







> Le 25 avr. 2015 à 18:08, Tilman Hausherr <THausherr@t-online.de> a écrit :
> 
> Hi,
> 
> Code doesn't work.
> 
> getTwelveFontSize, getTwentyFourFontSize, getEightyFieldWidth, getTwelveDefaultAppearance,
getSeventyFieldWidth are missing. And there is no main class (although it seems that one would
just instanciate the class)
> 
> Tilman
> 
> Am 24.04.2015 um 09:41 schrieb phiroc@free.fr:
>> Hi Tilman,
>> 
>> there's no need to change the coordinate values.
>> 
>> I must have made a mistake in my original code.
>> 
>> If you comment out setRotation() below, the page will be portraited. If you leave
setRotation(), it will be landscaped.
>> 
>> In both cases, the fields will be in the right direction.
>> 
>> Thanks for your input.
>> 
>> Best regards,
>> 
>> Philippe
>> 
>> -------------------------------------------------------------------------------------------
>> 
>> 
>> 
>> public class PdfTemplate0 {
>> 
>> 	protected final int		twelveFontSize					= 12;
>> 	protected final int		twentyFourFontSize				= 24;
>> 
>> 	protected final float	fortyFieldWidth					= 40f;
>> 	protected final float	seventyFieldWidth				= 70f;
>> 	protected final float	eightyFieldWidth				= 80f;
>> 	protected final float	oneHundredSixtyFieldWidth		= 160f;
>> 	protected final float	threeHundredFiftyFieldWidth		= 350f;
>> 	protected final float	threeHundredEightyFieldWidth	= 380f;
>> 	protected final float	fourHundredFieldWidth			= 400f;
>> 
>> 	protected String		twelveDefaultAppearance;
>> 	protected String		twentyFourDefaultAppearance;
>> 
>> 	public PdfTemplate0() {
>> 
>> 		final String RESULTS_FOLDER = "D:\\dev\\ProjectData\\fillbundlelabelformData\\pdf";
>> 		try {
>> 			byte[] template = generateSimpleTemplate(false);
>> 			Files.write(new File(RESULTS_FOLDER, "template.pdf").toPath(), template);
>> 
>> 		} catch (COSVisitorException e) {
>> 			e.printStackTrace();
>> 		} catch (IOException e) {
>> 			e.printStackTrace();
>> 		}
>> 	}
>> 
>> 	/* ***************************************************************** */
>> 
>> 	byte[] generateSimpleTemplate(final boolean addBarcode) throws IOException, COSVisitorException
{
>> 
>> 		final PDDocument template = new PDDocument();
>> 		final ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
>> 
>> 		final PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
>> 		page.setRotation(90);
>> 		template.addPage(page);
>> 
>> 		final PDFont font = PDType1Font.HELVETICA;
>> 		PDAcroForm acroForm = acroForm = new PDAcroForm(template);
>> 
>> 		final String fontName = setFontFormAndResources(acroForm, font, template);
>> 
>> 		setTwelveDefaultAppearance(setPdfDefaultAppearance(Integer.toString(getTwelveFontSize()),
fontName));
>> 		setTwentyFourDefaultAppearance(setPdfDefaultAppearance(Integer.toString(getTwentyFourFontSize()),
fontName));
>> 
>> 		createReportLineOne(page, acroForm);
>> 		
>> 
>> 		template.save(resultStream);
>> 		return resultStream.toByteArray();
>> 
>> 	} // end generateSimpleTemplate
>> 
>> 	/* ********************************************************************* */
>> 
>> 	protected void generateTemplatePdf(final String pathToGeneratedPdfDirectory) throws
COSVisitorException, IOException {
>> 
>> 		final byte[] templateWithoutBarcode = generateSimpleTemplate(false);
>> 		final byte[] templateWithBarcode = generateSimpleTemplate(true);
>> 
>> 		final PDDocument finalDoc0 = new PDDocument();
>> 		final PDDocument finalDoc1 = new PDDocument();
>> 
>> 		final PDDocument doc0 = PDDocument.load(new ByteArrayInputStream(templateWithoutBarcode));
>> 		final PDDocument doc1 = PDDocument.load(new ByteArrayInputStream(templateWithBarcode));
>> 
>> 		doc0.save(pathToGeneratedPdfDirectory + File.separator + "templateWithoutBarcode.pdf");
>> 		doc1.save(pathToGeneratedPdfDirectory + File.separator + "templateWithBarcode.pdf");
>> 
>> 		finalDoc0.close();
>> 		finalDoc1.close();
>> 
>> 	} // end generateTemplatePdf
>> 
>> 	/* ************************************************************************** */
>> 
>> 	protected COSDictionary createPdfCosDict(final float leftX, final float bottomY,
final float rightX, final float topY, final String da) {
>> 
>> 		final COSDictionary cosDict = new COSDictionary();
>> 
>> 		final COSArray rect = new COSArray();
>> 
>> 		// x and y start in the lower left
>> 		rect.add(new COSFloat(leftX)); // left x boundary
>> 		rect.add(new COSFloat(bottomY)); // bottom y boundary
>> 		rect.add(new COSFloat(rightX)); // right x boundary
>> 		rect.add(new COSFloat(topY)); // top 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));
>> 
>> 		return cosDict;
>> 
>> 	}
>> 
>> 	/* ********************************************************************* */
>> 
>> 	protected void createPdfTextbox(PDPage pDPage, PDAcroForm acroForm, final float
leftX, final float bottomY, final float rightX, final float topY,
>> 			final String defaultAppearanceString, final String textboxPartialName, final String
textboxValue) throws IOException {
>> 
>> 		final COSDictionary cosDictionary = createPdfCosDict(leftX, bottomY, rightX, topY,
defaultAppearanceString);
>> 
>> 		// add a form field to the form
>> 		final PDTextbox textbox = new PDTextbox(acroForm, cosDictionary);
>> 		textbox.setPartialName(textboxPartialName);
>> 
>> 		((List<PDField>) acroForm.getFields()).add(textbox);
>> 
>> 		// specify the annotation associated with the field
>> 		// and add it to the page
>> 		final PDAnnotationWidget widget = textbox.getWidget();
>> 		pDPage.getAnnotations().add(widget);
>> 
>> 		textbox.setValue(textboxValue);
>> 
>> 	}
>> 
>> 	/* ********************************************************************* */
>> 
>> 	protected String setPdfDefaultAppearance(final String fontSize, final String fontName)
{
>> 
>> 		final String defAp = "/" + fontName + " " + fontSize + " Tf 0 g";
>> 		return defAp;
>> 
>> 	}
>> 
>> 	/* ********************************************************************* */
>> 
>> 	protected String setFontFormAndResources(final PDAcroForm acroForm, PDFont font,
PDDocument template) {
>> 
>> 		template.getDocumentCatalog().setAcroForm(acroForm);
>> 
>> 		// Add and set the resources and default appearance
>> 		final PDResources res = new PDResources();
>> 		final String fontName = res.addFont(font);
>> 		acroForm.setDefaultResources(res);
>> 
>> 		return fontName;
>> 
>> 	}
>> 
>> 	/* ********************************************************************* */
>> 
>> 	protected void createReportLineOne(PDPage page, PDAcroForm acroForm) throws IOException
{
>> 
>> 		// leftX, bottomY, rightX, topY
>> 		createPdfTextbox(page, acroForm, 20f, 770f, getEightyFieldWidth() + 20f, 800f,
getTwelveDefaultAppearance(), "DATDELIVRY", "21 MAR 2015");
>> 		createPdfTextbox(page, acroForm, 110f, 770f, getSeventyFieldWidth() + 110f, 800f,
getTwelveDefaultAppearance(), "DLVROUTE.CODDLVMANI", "VAN4");
>> 		createPdfTextbox(page, acroForm, 190f, 770f, getSeventyFieldWidth() + 190f, 800f,
getTwelveDefaultAppearance(), "DLVROUTE.CODDLVDROP",
>> 				"10095");
>> 		createPdfTextbox(page, acroForm, 270f, 770f, getSeventyFieldWidth() + 270f, 800f,
getTwelveDefaultAppearance(), "BUNDLEPOSI", "1");
>> 		createPdfTextbox(page, acroForm, 350f, 770f, getSeventyFieldWidth() + 350f, 800f,
getTwelveDefaultAppearance(), "NBRBUNDLES", "1");
>> 		createPdfTextbox(page, acroForm, 430f, 770f, getSeventyFieldWidth() + 430f, 800f,
getTwelveDefaultAppearance(), "QUANTITCOP", "3");
>> 		createPdfTextbox(page, acroForm, 510f, 770f, getSeventyFieldWidth() + 510f, 800f,
getTwelveDefaultAppearance(), "QTYPRINTED", "3");
>> 
>> 	}
>> ...
>> 
>> 
>> -------------------------------------------------------------------------------------------
>> 
>> 
>> 
>> ----- Mail original -----
>> De: "Tilman Hausherr" <THausherr@t-online.de>
>> À: users@pdfbox.apache.org
>> Envoyé: Mercredi 22 Avril 2015 23:09:15
>> Objet: Re: Rotate text
>> 
>> I found this in the PDF spec for BBox:
>> /
>> //A rectangle in default user space coordinates specifying the location
>> of the viewport on the page.//
>> //The two coordinate pairs of the rectangle shall be specified in
>> normalized form; that is, lower-left followed by upper-right, relative
>> to the measuring coordinate system. This ordering shall determine the
>> orientation of the measuring coordinate system (that is, the direction
>> of the positive x and yaxes) in this viewport, which may have a
>> different rotation from the page./
>> 
>> 
>> So my understanding is that instead of 0,0,100,100 you should try e.g.
>> 0,100,100,0 or 100,0,0,100 for the BBox.
>> 
>> I didn't test it myself because your code isn't complete. Please tell
>> whether it worked or not.
>> 
>> Tilman
>> 
>> 
>> Am 22.04.2015 um 10:39 schrieb phiroc@free.fr:
>>> Hello,
>>> 
>>> when I generate the PDF using this method, the page is landscaped but not the
input field text.
>>> 
>>> How do I rotate the text?
>>> 
>>> Many thanks.
>>> 
>>> Philippe
>>> 
>>> ----------------------------------
>>> 
>>> 	byte[] generateSimpleTemplate() throws IOException, COSVisitorException {
>>> 
>>> 		try (PDDocument template = new PDDocument();
>>> 				InputStream fontStream = getClass().getResourceAsStream("/META-INF/fonts/arial.ttf");
>>> 				ByteArrayOutputStream resultStream = new ByteArrayOutputStream()) {
>>> 			final PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
>>> 			page.setRotation(90);
>>> 			template.addPage(page);
>>> 
>>> 			final PDTrueTypeFont font = PDTrueTypeFont.loadTTF(template, fontStream);
>>> 
>>> 			// add a new AcroForm and add that to the document
>>> 			final PDAcroForm acroForm = new PDAcroForm(template);
>>> 			template.getDocumentCatalog().setAcroForm(acroForm);
>>> 
>>> 			// Add and set the resources and default appearance
>>> 			final PDResources res = new PDResources();
>>> 			final String fontName = res.addFont(font);
>>> 			acroForm.setDefaultResources(res);
>>> 			final String da = "/" + fontName + " 12 Tf 0 g";
>>> 
>>> 			final COSDictionary cosDict = new COSDictionary();
>>> 
>>> 			final COSArray rect = new COSArray();
>>> 
>>> 			rect.add(new COSFloat(0f)); // lower x boundary
>>> 			rect.add(new COSFloat(0f)); // lower y boundary
>>> 			rect.add(new COSFloat(100f)); // upper x boundary
>>> 			rect.add(new COSFloat(100f)); // 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
>>> 			final PDTextbox textBox = new PDTextbox(acroForm, cosDict);
>>> 			textBox.setPartialName("SampleField");
>>> 
>>> ---------------------------------------
>>> 
>>> ---------------------------------------------------------------------
>>> To unsubscribe, e-mail: users-unsubscribe@pdfbox.apache.org
>>> For additional commands, e-mail: users-help@pdfbox.apache.org
>>> 
>> 
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: users-unsubscribe@pdfbox.apache.org
>> For additional commands, e-mail: users-help@pdfbox.apache.org
>> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe@pdfbox.apache.org
> For additional commands, e-mail: users-help@pdfbox.apache.org
> 


Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message