Skip to content

Instantly share code, notes, and snippets.

@johnnywey
Created April 15, 2014 19:29
Show Gist options
  • Save johnnywey/10762992 to your computer and use it in GitHub Desktop.
Save johnnywey/10762992 to your computer and use it in GitHub Desktop.
Add A White Background to a PDF File Using Groovy and iText
import com.itextpdf.text.*
import com.itextpdf.text.pdf.*
@Grab(group='com.itextpdf', module='itextpdf', version='5.5.0')
@Grab(group='org.bouncycastle', module='bcpkix-jdk15on', version='1.49')
class AddBackgroundColorToPdf {
static def createPdfFromImageFile(String fileName) {
def input = new FileInputStream(fileName)
PdfReader reader = new PdfReader(input)
int pages = reader.getNumberOfPages()
Rectangle pageSetup = reader.getPageSize(1)
pageSetup.setBackgroundColor(BaseColor.WHITE)
Document document = new Document(pageSetup, 0, 0, 0, 0)
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("./test-modified.pdf"));
document.open()
PdfImportedPage page
for (int i = 1; i <= pages; i++) {
page = writer.getImportedPage(reader, i)
document.add(Image.getInstance(page))
}
document.close()
}
static void main(String[] args) {
createPdfFromImageFile args[0]
}
}
@johnnywey
Copy link
Author

Results in test-modified.pdf having the updated PDF.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment