You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pdfbox.apache.org by le...@apache.org on 2010/12/11 17:43:49 UTC

svn commit: r1044678 - in /pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox: examples/pdmodel/AddMessageToEachPage.java pdmodel/common/COSStreamArray.java pdmodel/edit/PDPageContentStream.java

Author: lehmi
Date: Sat Dec 11 16:43:49 2010
New Revision: 1044678

URL: http://svn.apache.org/viewvc?rev=1044678&view=rev
Log:
PDFBOX-854: added a possibility to reset the graphics state of an existing contentstream before adding new content

Modified:
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMessageToEachPage.java
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/COSStreamArray.java
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/edit/PDPageContentStream.java

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMessageToEachPage.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMessageToEachPage.java?rev=1044678&r1=1044677&r2=1044678&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMessageToEachPage.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/examples/pdmodel/AddMessageToEachPage.java Sat Dec 11 16:43:49 2010
@@ -68,24 +68,41 @@ public class AddMessageToEachPage
 
             List allPages = doc.getDocumentCatalog().getAllPages();
             PDFont font = PDType1Font.HELVETICA_BOLD;
-            float fontSize = 12.0f;
+            float fontSize = 36.0f;
 
             for( int i=0; i<allPages.size(); i++ )
             {
                 PDPage page = (PDPage)allPages.get( i );
                 PDRectangle pageSize = page.findMediaBox();
-                float stringWidth = font.getStringWidth( message );
-                float centeredPosition = (pageSize.getWidth() - (stringWidth*fontSize)/1000f)/2f;
-                PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);
+                float stringWidth = font.getStringWidth( message )*fontSize/1000f;
+                // calculate to center of the page
+                int rotation = page.findRotation(); 
+                boolean rotate = rotation == 90 || rotation == 270;
+                float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
+                float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
+                double centeredXPosition = rotate ? pageHeight/2f : (pageWidth - stringWidth)/2f;
+                double centeredYPosition = rotate ? (pageWidth - stringWidth)/2f : pageHeight/2f;
+                // append the content to the existing stream
+                PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true,true);
                 contentStream.beginText();
+                // set font and font size
                 contentStream.setFont( font, fontSize );
-                contentStream.moveTextPositionByAmount( centeredPosition, 30 );
+                // set text color to red
+                contentStream.setNonStrokingColor(255, 0, 0);
+                if (rotate)
+                {
+                    // rotate the text according to the page rotation
+                    contentStream.setTextRotation(Math.PI/2, centeredXPosition, centeredYPosition);
+                }
+                else
+                {
+                    contentStream.setTextTranslation(centeredXPosition, centeredYPosition);
+                }
                 contentStream.drawString( message );
                 contentStream.endText();
                 contentStream.close();
             }
 
-
             doc.save( outfile );
         }
         finally

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/COSStreamArray.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/COSStreamArray.java?rev=1044678&r1=1044677&r2=1044678&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/COSStreamArray.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/common/COSStreamArray.java Sat Dec 11 16:43:49 2010
@@ -83,7 +83,7 @@ public class COSStreamArray extends COSS
     /**
      * This will get the number of streams in the array.
      *
-     * @return the numer of streams
+     * @return the number of streams
      */
     public int getStreamCount()
     {
@@ -130,8 +130,7 @@ public class COSStreamArray extends COSS
      */
     public String toString()
     {
-        String result = "COSStream{}";
-        return result;
+        return "COSStream{}";
     }
 
     /**
@@ -177,17 +176,6 @@ public class COSStreamArray extends COSS
     public InputStream getFilteredStream() throws IOException
     {
         throw new IOException( "Error: Not allowed to get filtered stream from array of streams." );
-        /**
-        Vector inputStreams = new Vector();
-        byte[] inbetweenStreamBytes = "\n".getBytes();
-
-        for( int i=0;i<streams.size(); i++ )
-        {
-            COSStream stream = (COSStream)streams.getObject( i );
-        }
-
-        return new SequenceInputStream( inputStreams.elements() );
-        **/
     }
 
     /**
@@ -199,7 +187,7 @@ public class COSStreamArray extends COSS
      */
     public InputStream getUnfilteredStream() throws IOException
     {
-        Vector inputStreams = new Vector();
+        Vector<InputStream> inputStreams = new Vector<InputStream>();
         byte[] inbetweenStreamBytes = "\n".getBytes();
 
         for( int i=0;i<streams.size(); i++ )
@@ -308,5 +296,18 @@ public class COSStreamArray extends COSS
     {
         streams.add(streamToAppend);
     }
+    
+    /**
+     * Insert the given stream at the beginning of the existing stream array.
+     * @param streamToBeInserted
+     */
+    public void insertCOSStream(PDStream streamToBeInserted)
+    {
+        COSArray tmp = new COSArray();
+        tmp.add(streamToBeInserted);
+        tmp.addAll(streams);
+        streams.clear();
+        streams = tmp;
+    }
 
 }

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/edit/PDPageContentStream.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/edit/PDPageContentStream.java?rev=1044678&r1=1044677&r2=1044678&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/edit/PDPageContentStream.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/edit/PDPageContentStream.java Sat Dec 11 16:43:49 2010
@@ -29,6 +29,8 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.pdfbox.cos.COSArray;
 import org.apache.pdfbox.cos.COSDictionary;
 import org.apache.pdfbox.cos.COSName;
@@ -61,6 +63,11 @@ import org.apache.pdfbox.util.MapUtil;
  */
 public class PDPageContentStream
 {
+    /**
+     * Log instance.
+     */
+    private static final Log log = LogFactory.getLog(PDPageContentStream.class);
+
     private PDPage page;
     private OutputStream output;
     private boolean inTextMode = false;
@@ -154,6 +161,22 @@ public class PDPageContentStream
     public PDPageContentStream( PDDocument document, PDPage sourcePage, boolean appendContent, boolean compress )
         throws IOException
     {
+        this(document,sourcePage,appendContent,compress,false);
+    }
+    /**
+     * Create a new PDPage content stream.
+     *
+     * @param document The document the page is part of.
+     * @param sourcePage The page to write the contents to.
+     * @param appendContent Indicates whether content will be overwritten. If false all previous content is deleted.
+     * @param compress Tell if the content stream should compress the page contents.
+     * @param resetContext Tell if the graphic context should be reseted.
+     * @throws IOException If there is an error writing to the page contents.
+     */
+    public PDPageContentStream( PDDocument document, PDPage sourcePage, boolean appendContent, boolean compress, boolean resetContext )
+            throws IOException
+    {
+        
         page = sourcePage;
         resources = page.getResources();
         if( resources == null )
@@ -170,12 +193,14 @@ public class PDPageContentStream
         xobjects = resources.getXObjects();
         xobjectMappings = reverseMap(xobjects, PDXObject.class);
 
+        // Get the pdstream from the source page instead of creating a new one
+        PDStream contents = sourcePage.getContents();
+        boolean hasContent = contents != null;
+
         // If request specifies the need to append to the document
-        if(appendContent)
+        if(appendContent && hasContent)
         {
-            // Get the pdstream from the source page instead of creating a new one
-            PDStream contents = sourcePage.getContents();
-
+            
             // Create a pdstream to append new content
             PDStream contentsToAppend = new PDStream( document );
 
@@ -199,21 +224,48 @@ public class PDPageContentStream
 
             if( compress )
             {
-                List filters = new ArrayList();
+                List<COSName> filters = new ArrayList<COSName>();
                 filters.add( COSName.FLATE_DECODE );
                 contentsToAppend.setFilters( filters );
             }
 
+            if (resetContext)
+            {
+                // create a new stream to encapsulate the existing stream 
+                PDStream saveGraphics = new PDStream( document );
+                output = saveGraphics.createOutputStream();
+                // save the initial/unmodified graphics context
+                saveGraphicsState();
+                close();
+                if( compress )
+                {
+                    List<COSName> filters = new ArrayList<COSName>();
+                    filters.add( COSName.FLATE_DECODE );
+                    saveGraphics.setFilters( filters );
+                }
+                // insert the new stream at the beginning
+                compoundStream.insertCOSStream(saveGraphics);
+            }
+
             // Sets the compoundStream as page contents
             sourcePage.setContents( new PDStream(compoundStream) );
             output = contentsToAppend.createOutputStream();
+            if (resetContext)
+            {
+                // restore the initial/unmodified graphics context
+                restoreGraphicsState();
+            }
         }
         else
         {
-            PDStream contents = new PDStream( document );
+            if (hasContent)
+            {
+                log.warn("You are overwriting an existing content, you should use the append mode");
+            }
+            contents = new PDStream( document );
             if( compress )
             {
-                List filters = new ArrayList();
+                List<COSName> filters = new ArrayList<COSName>();
                 filters.add( COSName.FLATE_DECODE );
                 contents.setFilters( filters );
             }