title: PDF scaling/importing pages that have been trimmed/cropped
body: <p>I am currently in the process of writing an app that "formats" PDF's to our requirements, using iText 2.1.7.</p>
  
  <p>We basically take a portrait PDF, and scale down the pages, so we can fit 2 pages of the original PDF, on one landscape page of the new PDF. We also leave some space at the bottom of the page which is used for post processing.</p>
  
  <p>This process works 90% of the time as it should.</p>
  
  <p>However, we received a PDF that has been cropped/trimmed by the content department, and when we view this PDF in Acrobat, it looks as excpected. However, when we process it, the new PDF includes the entire original MediaBox, and the crop lines.</p>
  
  <p>Here is the code we use, and how a problem output looks.</p>
  
  <pre><code>File tempFile = new File(tempFilename);
  PdfReader reader = new PdfReader(originalPdfFile);
  Document doc = new Document(new RectangleReadOnly(842f, 595f), 0, 0, 0, 0);
  PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(tempFile));
  doc.open();
  for (int i = 1; i &lt; reader.getNumberOfPages(); i = i + 2) {
      doc.newPage();
      PdfContentByte cb = writer.getDirectContent();
      PdfImportedPage page = writer.getImportedPage(reader, i); // page #1
  
      float documentWidth = doc.getPageSize().getWidth() / 2;
      float documentHeight = doc.getPageSize().getHeight() - 65f;
  
      float pageWidth = page.getWidth();
      float pageHeight = page.getHeight();
  
      float widthScale = documentWidth / pageWidth;
      float heightScale = documentHeight / pageHeight;
      float scale = Math.min(widthScale, heightScale);
  
      float offsetX = (documentWidth - (pageWidth * scale)) / 2;
      float offsetY = 65f; //100f
  
      cb.addTemplate(page, scale, 0, 0, scale, offsetX, offsetY);
  
      PdfImportedPage page2 = writer.getImportedPage(reader, i+1); // page #2
  
      pageWidth = page.getWidth();
      pageHeight = page.getHeight();
  
      widthScale = documentWidth / pageWidth;
      heightScale = documentHeight / pageHeight;
      scale = Math.min(widthScale, heightScale);
  
      offsetX = ((documentWidth - (pageWidth * scale)) / 2) + documentWidth;
      offsetY = 65f; //100f
  
      cb.addTemplate(page2, scale, 0, 0, scale, offsetX, offsetY);//430f
      }
  
  doc.close();
  </code></pre>
  
  <p>original in acrobat:</p>
  
  <p><img src="https://i.stack.imgur.com/cilSZ.jpg" alt="enter image description here"></p>
  
  <p>modified in acrobat, showing unwanted pretrim content:</p>
  
  <p><img src="https://i.stack.imgur.com/ebrEr.jpg" alt="enter image description here"></p>