Skip to content

Instantly share code, notes, and snippets.

@chtrinh
Created September 29, 2010 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chtrinh/602509 to your computer and use it in GitHub Desktop.
Save chtrinh/602509 to your computer and use it in GitHub Desktop.
/**
* What this does:
* converts current.docx to "current pdf"
* Adds a timestamp on the footer of each page of "current pdf"
* Appends the "current pdf" to comprehensive pdf
* Zip the "current pdf" to archive.zip
* Deletes the "current pdf"
*
* Usage example: java ELabnotes archive.zip comprehensive.pdf current.docx
*
* If you obtain an out of memory error expand your java runtime memory allocation.
*
* rsyntax 2010-29-9
*
This is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
Distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.*;
import java.util.*;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
public class ELabnotes {
public static final String tempFilename = "temp.pdf";
public static String getTimestamp()
{
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
return currentTimestamp.toString();
}
/** Inner class to add a header and a footer. */
static class HeaderFooter extends PdfPageEventHelper {
public void onEndPage (PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("TIMESTAMP_FOOTER");
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(getTimestamp()),
rect.getRight(), rect.getBottom() - 5, 0);
}
}
public static String convertPDF(String docxFilepath) throws Docx4JException, IOException
{
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(docxFilepath));
org.docx4j.convert.out.pdf.PdfConversion c
= new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
String pdfFilepath = docxFilepath.substring(0, docxFilepath.lastIndexOf(".")) + ".pdf";
OutputStream os = new java.io.FileOutputStream(pdfFilepath);
c.output(os);
System.out.println("Saved " + pdfFilepath);
return pdfFilepath;
}
public static PdfReader addTimestampFooter(String pdfFilepath) throws IOException, DocumentException
{
PdfReader reader1 = new PdfReader(pdfFilepath);
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(tempFilename));
// Set Footer, add a timestamp
writer.setBoxSize("TIMESTAMP_FOOTER", new Rectangle(36, 54, 500, 788));
HeaderFooter event = new HeaderFooter();
writer.setPageEvent(event);
document.open();
PdfContentByte cb = writer.getDirectContent(); // Holds the PDF data
PdfImportedPage page;
for(int i = 1; i <= reader1.getNumberOfPages(); i++)
{
document.newPage();
page = writer.getImportedPage(reader1, i);
cb.addTemplate(page, 0, 0);
}
document.close();
writer.close();
// Delete old pdf and rename new pdf
File f = new File(pdfFilepath);
f.delete();
f = new File(tempFilename);
f.renameTo(new File(pdfFilepath));
System.out.println("Add timestamp to " + pdfFilepath);
return new PdfReader(pdfFilepath);
}
public static void main(String[] args) {
try {
String archiveFilepath = args[0];
String largePDFPath = args[1];
// String srcPDFPath = args[2];
String srcPDFPath = convertPDF(args[2]);
ZipUtil z = new ZipUtil(archiveFilepath);
PdfReader alteredPDF = addTimestampFooter(srcPDFPath);
PdfReader largePDF = new PdfReader(largePDFPath);
PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(tempFilename));
copy.addDocument(largePDF);
copy.addDocument(alteredPDF);
copy.close();
// Delete old pdf and rename new pdf
File f = new File(largePDFPath);
f.delete();
f = new File(tempFilename);
f.renameTo(new File(largePDFPath));
System.out.println("Append " + srcPDFPath + " to " + largePDFPath);
z.appendZip(srcPDFPath);
System.out.println("Archiving " + srcPDFPath + " to " + archiveFilepath);
f = new File(srcPDFPath);
f.delete();
System.out.println("Deleting " + srcPDFPath);
} catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}catch (IOException e)
{
System.out.println(e.getMessage());
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* Implementation done by
* sfussenegge from Stackoverflow.com
*
* modifications: rsyntax 2010-29-9
*
This is licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
Distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
// 4MB buffer
private static final int BUFFER_SIZE = 4096 * 1024;
private static final byte[] BUFFER = new byte[BUFFER_SIZE];
private String zipFilepath;
public ZipUtil(String zipFilepath)
{
this.zipFilepath = zipFilepath;
}
/**
* copy input to output stream - available in several StreamUtils or Streams classes
*/
private void copy(InputStream input, OutputStream output) throws IOException {
int bytesRead;
while ((bytesRead = input.read(BUFFER))!= -1) {
output.write(BUFFER, 0, bytesRead);
}
}
public void appendZip(String filepath) throws Exception {
File f = new File(zipFilepath);
if(f.exists())
{
// read war.zip and write to append.zip
ZipFile war = new ZipFile(zipFilepath);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream("archive.dat"));
// first, copy contents from existing war
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
// now append some extra content
ZipEntry e = new ZipEntry(filepath);
FileInputStream fi = new FileInputStream(filepath);
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER_SIZE);
append.putNextEntry(e);
int count;
while((count = origin.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
append.write(BUFFER, 0, count);
}
origin.close();
fi.close();
append.closeEntry();
// close
war.close();
append.close();
f = new File(zipFilepath);
f.delete();
f = new File("archive.dat");
f.renameTo(new File(zipFilepath));
}
else
{
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(new FileOutputStream(f)));
ZipEntry e = new ZipEntry(filepath);
FileInputStream fi = new FileInputStream(filepath);
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER_SIZE);
out.putNextEntry(e);
int count;
while((count = origin.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
out.write(BUFFER, 0, count);
}
origin.close();
fi.close();
out.closeEntry();
out.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment