use of com.lowagie.text.pdf.PdfImportedPage in project adempiere by adempiere.
the class AEnv method mergePdf.
/**
*
* @param pdfList
* @param outFile
* @throws IOException
* @throws DocumentException
* @throws FileNotFoundException
*/
public static void mergePdf(List<File> pdfList, File outFile) throws IOException, DocumentException, FileNotFoundException {
Document document = null;
PdfWriter copy = null;
for (File f : pdfList) {
PdfReader reader = new PdfReader(f.getAbsolutePath());
if (document == null) {
document = new Document(reader.getPageSizeWithRotation(1));
copy = PdfWriter.getInstance(document, new FileOutputStream(outFile));
document.open();
}
int pages = reader.getNumberOfPages();
PdfContentByte cb = copy.getDirectContent();
for (int i = 1; i <= pages; i++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, i);
cb.addTemplate(page, 0, 0);
}
}
document.close();
}
use of com.lowagie.text.pdf.PdfImportedPage in project ofbiz-framework by apache.
the class CompDocServices method renderCompDocPdf.
public static Map<String, Object> renderCompDocPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
String rootDir = (String) context.get("rootDir");
String webSiteId = (String) context.get("webSiteId");
String https = (String) context.get("https");
Delegator delegator = dctx.getDelegator();
String contentId = (String) context.get("contentId");
String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
try {
List<EntityCondition> exprList = new LinkedList<EntityCondition>();
exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId));
exprList.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId));
if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
exprList.add(EntityCondition.makeCondition("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
}
List<GenericValue> compDocParts = EntityQuery.use(delegator).select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum").from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate().queryList();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
document.setPageSize(PageSize.LETTER);
PdfCopy writer = new PdfCopy(document, baos);
document.open();
for (GenericValue contentAssocRevisionItemView : compDocParts) {
String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", thisDataResourceId).queryOne();
String inputMimeType = null;
if (dataResource != null) {
inputMimeType = dataResource.getString("mimeTypeId");
}
byte[] inputByteArray = null;
PdfReader reader = null;
if (inputMimeType != null && "application/pdf".equals(inputMimeType)) {
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
inputByteArray = byteBuffer.array();
reader = new PdfReader(inputByteArray);
} else if (inputMimeType != null && "text/html".equals(inputMimeType)) {
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
inputByteArray = byteBuffer.array();
String s = new String(inputByteArray, "UTF-8");
Debug.logInfo("text/html string:" + s, module);
continue;
} else if (inputMimeType != null && "application/vnd.ofbiz.survey.response".equals(inputMimeType)) {
String surveyResponseId = dataResource.getString("relatedDetailId");
String surveyId = null;
String acroFormContentId = null;
GenericValue surveyResponse = null;
if (UtilValidate.isNotEmpty(surveyResponseId)) {
surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
}
if (UtilValidate.isNotEmpty(surveyId)) {
GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
if (survey != null) {
acroFormContentId = survey.getString("acroFormContentId");
if (UtilValidate.isNotEmpty(acroFormContentId)) {
// TODO: is something supposed to be done here?
}
}
}
if (surveyResponse != null) {
if (UtilValidate.isEmpty(acroFormContentId)) {
// Create AcroForm PDF
Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId));
if (ServiceUtil.isError(survey2PdfResults)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
}
ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
reader = new PdfReader(inputByteArray);
} else {
// Fill in acroForm
Map<String, Object> survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
if (ServiceUtil.isError(survey2AcroFieldResults)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults);
}
ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
reader = new PdfReader(inputByteArray);
}
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale));
}
if (reader != null) {
int n = reader.getNumberOfPages();
for (int i = 0; i < n; i++) {
PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
writer.addPage(pg);
}
}
}
document.close();
ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("outByteBuffer", outByteBuffer);
return results;
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.toString());
} catch (IOException | DocumentException | GeneralException e) {
Debug.logError(e, "Error in CompDoc operation: ", module);
return ServiceUtil.returnError(e.toString());
}
}
use of com.lowagie.text.pdf.PdfImportedPage in project jaffa-framework by jaffa-projects.
the class PdfHelper method removeRotation.
/**
* Remove the rotation from the pdfOutput document pages.
*/
private static byte[] removeRotation(byte[] pdfOutput) throws FormPrintException {
PdfReader currentReader = null;
try {
currentReader = new PdfReader(pdfOutput);
} catch (IOException ex) {
FormPrintException e = new PdfProcessingException("Remove PDF Page Rotation - Failed to create a PDF Reader");
log.error(" Remove PDF Page Rotation - Failed to create a PDF Reader ");
throw e;
}
boolean needed = false;
for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
if (currentReader.getPageRotation(i) != 0) {
needed = true;
}
}
if (!needed) {
return pdfOutput;
}
OutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, baos);
} catch (DocumentException ex) {
FormPrintException e = new PdfProcessingException("Remove PDF Page Rotation - Failed to create a PDF Writer");
log.error(" Remove PDF Page Rotation - Failed to create a PDF Writer ");
throw e;
}
PdfContentByte cb = null;
PdfImportedPage page;
for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
// strip rotation
currentSize = new Rectangle(currentSize.getWidth(), currentSize.getHeight());
document.setPageSize(currentSize);
if (cb == null) {
document.open();
cb = writer.getDirectContent();
} else {
document.newPage();
}
int rotation = currentReader.getPageRotation(i);
page = writer.getImportedPage(currentReader, i);
float a, b, c, d, e, f;
if (rotation == 0) {
a = 1;
b = 0;
c = 0;
d = 1;
e = 0;
f = 0;
} else if (rotation == 90) {
a = 0;
b = -1;
c = 1;
d = 0;
e = 0;
f = currentSize.getHeight();
} else if (rotation == 180) {
a = -1;
b = 0;
c = 0;
d = -1;
e = currentSize.getWidth();
f = currentSize.getHeight();
} else if (rotation == 270) {
a = 0;
b = 1;
c = -1;
d = 0;
e = currentSize.getWidth();
f = 0;
} else {
FormPrintException ex = new PdfProcessingException("Remove PDF Page Rotation - Unparsable rotation value: " + rotation);
log.error(" Remove PDF Page Rotation - Unparsable form rotation value: " + rotation);
throw ex;
}
cb.addTemplate(page, a, b, c, d, e, f);
}
document.close();
return ((ByteArrayOutputStream) baos).toByteArray();
}
use of com.lowagie.text.pdf.PdfImportedPage in project jaffa-framework by jaffa-projects.
the class MultiFormPrintEngine method mergePdf.
/**
* Merge a list of generated Pdf Documents together
* @param documents
* @throws java.io.IOException
* @throws com.lowagie.text.DocumentException
* @return byte[]
*/
public static byte[] mergePdf(List<byte[]> documents) throws IOException, DocumentException {
int pageOffset = 0;
ArrayList master = new ArrayList();
ByteArrayOutputStream output = new ByteArrayOutputStream();
Document document = null;
PdfCopy writer = null;
boolean first = true;
for (Iterator<byte[]> it = documents.iterator(); it.hasNext(); ) {
// we create a reader for a certain document
PdfReader reader = new PdfReader(it.next());
reader.consolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
List bookmarks = SimpleBookmark.getBookmark(reader);
if (bookmarks != null) {
if (pageOffset != 0)
SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
master.addAll(bookmarks);
}
pageOffset += n;
if (first) {
first = false;
// step 1: creation of a document-object
document = new Document(reader.getPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
writer = new PdfCopy(document, output);
// step 3: we open the document
document.open();
}
// step 4: we add content
PdfImportedPage page;
for (int i = 0; i < n; ) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
PRAcroForm form = reader.getAcroForm();
if (form != null)
writer.copyAcroForm(reader);
}
if (master.size() > 0)
writer.setOutlines(master);
// step 5: we close the document
if (document != null)
document.close();
return output.toByteArray();
}
use of com.lowagie.text.pdf.PdfImportedPage in project jaffa-framework by jaffa-projects.
the class PdfHelper method scalePdfPages.
/**
* Scale the pages of the input pdfOutput document to the given pageSize.
* @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream.
* @param pageSize The new page size to which to scale to PDF document, e.g. "A4".
* @param noEnlarge If true, center pages instead of enlarging them.
* Use noEnlarge if the new page size is larger than the old one
* and the pages should be centered instead of enlarged.
* @param preserveAspectRatio If true, the aspect ratio will be preserved.
* @return The PDF document with its pages scaled to the input pageSize.
*/
public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge, boolean preserveAspectRatio) throws FormPrintException {
if (pageSize == null || pdfOutput == null) {
return pdfOutput;
}
// Get the dimensions of the given pageSize in PostScript points.
// A PostScript point is a 72th of an inch.
float dimX;
float dimY;
Rectangle rectangle;
try {
rectangle = PageSize.getRectangle(pageSize);
} catch (Exception ex) {
FormPrintException e = new PdfProcessingException("scalePdfPages - Invalid page size = " + pageSize + " ");
log.error(" scalePdfPages - Invalid page size: " + pageSize + ". " + ex.getMessage() + ". ");
throw e;
}
if (rectangle != null) {
dimX = rectangle.getWidth();
dimY = rectangle.getHeight();
} else {
FormPrintException e = new PdfProcessingException("scalePdfPages - Invalid page size: " + pageSize);
log.error(" scalePdfPages - Invalid page size: " + pageSize);
throw e;
}
// Create portrait and landscape rectangles for the given page size.
Rectangle portraitPageSize;
Rectangle landscapePageSize;
if (dimY > dimX) {
portraitPageSize = new Rectangle(dimX, dimY);
landscapePageSize = new Rectangle(dimY, dimX);
} else {
portraitPageSize = new Rectangle(dimY, dimX);
landscapePageSize = new Rectangle(dimX, dimY);
}
// Remove the document rotation before resizing the document.
byte[] output = removeRotation(pdfOutput);
PdfReader currentReader = null;
try {
currentReader = new PdfReader(output);
} catch (IOException ex) {
FormPrintException e = new PdfProcessingException("scalePdfPages - Failed to create a PDF Reader");
log.error(" scalePdfPages - Failed to create a PDF Reader ");
throw e;
}
OutputStream baos = new ByteArrayOutputStream();
Rectangle newSize = new Rectangle(dimX, dimY);
Document document = new Document(newSize, 0, 0, 0, 0);
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, baos);
} catch (DocumentException ex) {
FormPrintException e = new PdfProcessingException("scalePdfPages - Failed to create a PDF Writer");
log.error(" scalePdfPages - Failed to create a PDF Writer ");
throw e;
}
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
float offsetX, offsetY;
for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
if (currentReader.getPageRotation(i) != 0) {
FormPrintException e = new PdfProcessingException("Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form.");
log.error(" Page Rotation, " + currentReader.getPageRotation(i) + ", must be removed to re-scale the form. ");
throw e;
}
// Reset the page size for each page because there may be a mix of sizes in the document.
float currentWidth = currentSize.getWidth();
float currentHeight = currentSize.getHeight();
if (currentWidth > currentHeight) {
newSize = landscapePageSize;
} else {
newSize = portraitPageSize;
}
document.setPageSize(newSize);
document.newPage();
float factorX = newSize.getWidth() / currentSize.getWidth();
float factorY = newSize.getHeight() / currentSize.getHeight();
// and the pages should be centered instead of enlarged.
if (noEnlarge) {
if (factorX > 1) {
factorX = 1;
}
if (factorY > 1) {
factorY = 1;
}
}
if (preserveAspectRatio) {
factorX = Math.min(factorX, factorY);
factorY = factorX;
}
offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f;
offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f;
page = writer.getImportedPage(currentReader, i);
cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY);
}
document.close();
return ((ByteArrayOutputStream) baos).toByteArray();
}
Aggregations