#java #itext
#java #itext
Вопрос:
Всякий раз, когда я запускаю приведенный ниже код на своем локальном компьютере, это работает так, как ожидалось, но когда я пытаюсь выполнить то же самое на сервере, в начале создаются пустые страницы, заголовок также не добавляется. Но если запись меньше и состоит из одной страницы, PDF-файл создается по желанию.
public class StatementPrintingTemp implements Serializable
{
private static final long serialVersionUID = 1L;
Font fontColour_bold = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.BOLD, BaseColor.BLACK);
Font fontColour_NormalUnderline = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL|Font.UNDERLINE, BaseColor.BLACK);
Font fontColour_Normal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 11, Font.NORMAL, BaseColor.BLACK);
Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 11, Font.BOLD, new BaseColor(0, 0, 0));
Font bf12 = new Font(FontFamily.TIMES_ROMAN, 9);
Font bf12bold = new Font(FontFamily.TIMES_ROMAN, 9,Font.BOLD);
Document doc = null;
@SuppressWarnings("unused")
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD, new BaseColor(130, 150, 60));
@SuppressWarnings("unused")
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
@SuppressWarnings("unused")
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.BOLD, BaseColor.BLACK);
private static Font smallNormal = FontFactory.getFont(FontFactory.TIMES_ROMAN, 7, Font.NORMAL, BaseColor.BLACK);
private static Logger logger = Logger.getLogger("consoleLogger");
static {
PropertyConfigurator.configure(System.getProperty("user.dir") File.separator "Config" File.separator
"log4j_WebServiceWrapper.properties");
// **********Read the attributes from NG_SERVICE.xml****************
String log4jConfigFile = "";
logger = Logger.getLogger("common_logger");
log4jConfigFile = System.getProperty("user.dir") File.separator "log4j.properties";
PropertyConfigurator.configure(log4jConfigFile);
}
public String executetemp(String workitemName,String salno, String templatename, String sessionid, String processName) {
DMSOperation objDmsOper = null;
ReadServerProperty prop = null;
String outputXML = "";
WFSession wfSession = null;
Properties property = null;
String propFilePath = System.getProperty("user.dir") File.separator "Config" File.separator
"serverdetail.properties";
logger.info("propFilePath = " propFilePath);
System.out.print(propFilePath);
try {
wfSession = new WFSession();
objDmsOper = new DMSOperation();
property = new Properties();
property.load(new FileInputStream(propFilePath));
String serverPath = property.getProperty("TEMPLATEUTILPATH");
logger.info("Server Path " serverPath);
PropertyConfigurator.configure(serverPath "/TemplateGeneration/log4j.properties");
logger.info("Logging configured");
prop = new ReadServerProperty(propFilePath);
// Create Connection
if (objDmsOper.createNGEJBConnection(prop)) {
if (objDmsOper.connecttoDMS(sessionid)) {
outputXML = generateTemplate(wfSession, objDmsOper, prop, workitemName,salno,templatename , serverPath, processName);
}
}
} catch (Exception e) {
logger.info("Error in main:" CommonFunctions.getStackTrace(e));
} finally {
objDmsOper = null;
prop = null;
property = null;
wfSession = null;
}
return outputXML;
}
public String generateTemplate(WFSession wfSession, DMSOperation objDmsOper, ReadServerProperty prop,
String workitemName,String salno, String templateName, String serverPath,String ProcessName)
{
String sDOCAddXML ="";
PdfWriter docWriter = null;
String path = "";
String sCurrentDate="";
String WI_NUMBER = "";
String ACCOUNT_STATUS ="";
String ACCT_OPEN_DATE="";
XMLParser parserObj = new XMLParser();
XMLParser parser = new XMLParser();
@SuppressWarnings("unused")
String TRAN_DATE="",VALUE_DATE="",CHQ_NUM="",TRAN_DESC="",ACCT_CURR_CODE="",DEBIT_AMT="",CREDIT_AMT="",BAL_AMT="",FROM_DATE="",OPENING_BAL="",CLOSING_BAL="",ACCT_NAME="",ACC="";
String newdt= "";
String todt= "";
try
{
logger.info("salno : " salno);
logger.info("workitemName : " workitemName "ntemplateName : " templateName);
String queryString = "Select WI_NUMBER,COUNTRY,CIF_ID,WI_NO,INITIATED_BY,convert (VARCHAR,convert(DATE,WI_INIT_DT),103) AS WI_INIT_DT,APP_NAME,ACC_NO,G_HOME_BRANCH_NAME,ACCOUNT_STATUS, ACCT_OPEN_DATE,format(getdate(),'dd-MM-yyyy') AS ACCT_STATUS_DATE,ACCT_CLOSING_DATE,format(FROM_DATE,'dd-MM-yyyy') AS FROM_DATE,format(TO_DATE,'dd-MM-yyyy') AS TO_DATE,PO_BOX,POSTAL_CODE,CITY, AREA,format(getdate(),'dd/MM/yyyy HH:mm:ss') AS CURRENTDATE,FOLDERINDEX FROM BD_SP_EXTTABLE WHERE WI_NO ='" workitemName "'";
String outputXML = objDmsOper.dbValues(queryString, prop);
parserObj.setInputXML((outputXML));
logger.info("queryString 1 is--" queryString);
logger.info("outputXML is--" outputXML);
logger.info("After query STring : " );
String Name =parserObj.getValueOf("APP_NAME");
ACCOUNT_STATUS =parserObj.getValueOf("ACCOUNT_STATUS");
logger.info("ACCOUNT_STATUS : " ACCOUNT_STATUS);
ACCT_OPEN_DATE =parserObj.getValueOf("ACCT_OPEN_DATE");
logger.info("ACCT_OPEN_DATE is--" ACCT_OPEN_DATE);
WI_NUMBER =parserObj.getValueOf("WI_NUMBER");
logger.info("WI_NUMBER: " WI_NUMBER);
String POBOX =parserObj.getValueOf("PO_BOX");
String PC =parserObj.getValueOf("POSTAL_CODE");
String City = parserObj.getValueOf("CITY") "," parserObj.getValueOf("AREA");
String Country ="SULTANATE OF OMAN";
//parserObj.getValueOf("COUNTRY");
String sAccountNo =salno;
String initiatedby =parserObj.getValueOf("INITIATED_BY");
String wi_no =workitemName;
//String Area=parserObj.getValueOf("AREA");
newdt= parserObj.getValueOf("FROM_DATE");
sCurrentDate= parserObj.getValueOf("CURRENTDATE");
todt= parserObj.getValueOf("TO_DATE");
logger.info("newdt : " newdt "ntodt : " todt);
String queryChq = "select TRAN_DATE,VALUE_DATE,CHQ_NUM,TRAN_DESC,ACCT_CURR_CODE,DEBIT_AMT,CREDIT_AMT,BAL_AMT,FROM_DATE,OPENING_BAL,CLOSING_BAL,ACCT_NAME,ACC AS ACC_NO,getdate()'ACC_STATUS_DATE' FROM openquery(bpmfin,'select * from table ( custom.get_acc_stm_mfk(''" salno "'', to_date(''" newdt "'',''DD-MM-YYYY''), to_date(''" todt "'',''DD-MM-YYYY'')))')";
logger.info("queryChq : " queryChq);
String sQueryChq = objDmsOper.dbValues(queryChq, prop);
logger.info("sQueryChq : " sQueryChq);
parser = new XMLParser();
parser.setInputXML(sQueryChq);
logger.info("sQueryChq : " newdt "ntodt : " todt);
String ACC_STATUS_DATE=parser.getValueOf("ACC_STATUS_DATE");
logger.info("ACC_STATUS_DATE : " ACC_STATUS_DATE);
int Record =0;
if(parser.getValueOf("MainCode").equalsIgnoreCase("0"))
{
Record = Integer.parseInt(parser.getValueOf("TotalRetrieved"));
}
if(Record>0)
{
Name = parser.getValueOf("ACCT_NAME");
}
int TotalPages =1;
/*if(Record<=44)
{
TotalPages = 1;
}
else
{
double remain = Record - 44;
TotalPages = (int) Math.ceil(remain/52) 1;
}*/
logger.info("TOtal Pages : " TotalPages);
Document doc = new Document();
docWriter = null;
String destinationpath = System.getProperty("user.dir") "\TemplateGeneration\generatedTemplates\" workitemName;
File dirpath = new File(destinationpath);
logger.info("destinationpath before-->>" destinationpath);
if(dirpath == null || !dirpath.isDirectory())
{
dirpath.mkdir();
}
//file path
path = System.getProperty("user.dir") "\TemplateGeneration\generatedTemplates\" workitemName "\" templateName ".pdf";
logger.info("PATH : " path);
docWriter = PdfWriter.getInstance(doc , new FileOutputStream(path));
if (parserObj.getValueOf("MainCode").equalsIgnoreCase("0"))
{
try {
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(path));
doc.setPageSize(PageSize.LETTER);
doc.setMargins(25, 25, 160, 40);
Rectangle rect = new Rectangle(PageSize.A4);
writer.setBoxSize("art", rect);
HeaderFooterPageEvent event = new HeaderFooterPageEvent(Name,POBOX,PC,City,Country ,initiatedby,wi_no,sAccountNo,TotalPages,sCurrentDate);
writer.setPageEvent(event);
doc.open();
Paragraph heading = new Paragraph();
float[] columnWidthsTop = {3f, 3f, 3f,3f};
//create PDF table with the given widths
PdfPTable tableTop = new PdfPTable(columnWidthsTop);
// set table width a percentage of the page width
tableTop.setWidthPercentage(100f);
insertCell(tableTop, "A/c.Status", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, ACCOUNT_STATUS, Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "A/c.Status Date", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, ACC_STATUS_DATE, Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "A/c. Open Date", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, ACCT_OPEN_DATE, Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "A/c. Close Date", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, "NA", Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "Opening Balance ", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, parser.getFirstValueOf("OPENING_BAL"), Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "Available Amount", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, parser.getFirstValueOf("CLOSING_BAL"), Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "Closing Balance ", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, parser.getFirstValueOf("CLOSING_BAL"), Element.ALIGN_LEFT, 1, bf12,false,false);
insertCell(tableTop, "Effective Available Amount", Element.ALIGN_LEFT, 1, bf12bold,false,false);
insertCell(tableTop, parser.getFirstValueOf("BAL_AMT"), Element.ALIGN_LEFT, 1, bf12,false,false);
doc.add(tableTop);
heading = new Paragraph();
addEmptyLine(heading, 2);
doc.add(heading);
float[] columnWidths = {6f,6f,11f,33f,3f,8f,8f,7f};
PdfPTable table = new PdfPTable(columnWidths);
table.setWidthPercentage(100f);
insertCell(table, "Tran.Date", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "Value Date", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "Instr.No", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "Particulars", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "CCY", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "Debit Amount", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "Credit Amount", Element.ALIGN_CENTER, 1, smallBold,true,true);
insertCell(table, "Balance", Element.ALIGN_CENTER, 1, smallBold,true,true);
table.setHeaderRows(1);
if(Record>0)
{
TRAN_DATE="";VALUE_DATE="";CHQ_NUM="";TRAN_DESC="";ACCT_CURR_CODE="";DEBIT_AMT="";CREDIT_AMT="";BAL_AMT="";FROM_DATE="";OPENING_BAL="";CLOSING_BAL="";ACCT_NAME="";ACC="";
if(Record==1)
{
TRAN_DATE=parser.getValueOf("TRAN_DATE");
VALUE_DATE=parser.getValueOf("VALUE_DATE");
CHQ_NUM=parser.getValueOf("CHQ_NUM");
TRAN_DESC=parser.getValueOf("TRAN_DESC");
ACCT_CURR_CODE=parser.getValueOf("ACCT_CURR_CODE");
DEBIT_AMT=parser.getValueOf("DEBIT_AMT");
CREDIT_AMT=parser.getValueOf("CREDIT_AMT");
BAL_AMT=parser.getValueOf("BAL_AMT");
FROM_DATE=parser.getValueOf("FROM_DATE");
OPENING_BAL=parser.getValueOf("OPENING_BAL");
CLOSING_BAL=parser.getValueOf("CLOSING_BAL");
ACCT_NAME=parser.getValueOf("ACCT_NAME");
ACC=parser.getValueOf("ACC");
insertCell(table, TRAN_DATE, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, VALUE_DATE, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, CHQ_NUM, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, TRAN_DESC, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, ACCT_CURR_CODE, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, DEBIT_AMT, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, CREDIT_AMT, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, BAL_AMT, Element.ALIGN_LEFT, 1, smallNormal,false,true);
}
else
{
String sXML ="";
for (int x=0; x<Record; x )
{
sXML = parser.getNextValueOf("Record");
XMLParser subParser = new XMLParser();
subParser.setInputXML(sXML);
TRAN_DATE="";VALUE_DATE="";CHQ_NUM="";TRAN_DESC="";ACCT_CURR_CODE="";DEBIT_AMT="";CREDIT_AMT="";BAL_AMT="";FROM_DATE="";OPENING_BAL="";CLOSING_BAL="";ACCT_NAME="";ACC="";
TRAN_DATE=subParser.getValueOf("TRAN_DATE");
VALUE_DATE=subParser.getValueOf("VALUE_DATE");
CHQ_NUM=subParser.getValueOf("CHQ_NUM");
TRAN_DESC=subParser.getValueOf("TRAN_DESC");
ACCT_CURR_CODE=subParser.getValueOf("ACCT_CURR_CODE");
DEBIT_AMT=subParser.getValueOf("DEBIT_AMT");
CREDIT_AMT=subParser.getValueOf("CREDIT_AMT");
BAL_AMT=subParser.getValueOf("BAL_AMT");
FROM_DATE=subParser.getValueOf("FROM_DATE");
OPENING_BAL=subParser.getValueOf("OPENING_BAL");
CLOSING_BAL=subParser.getValueOf("CLOSING_BAL");
ACCT_NAME=subParser.getValueOf("ACCT_NAME");
ACC=subParser.getValueOf("ACC");
insertCell(table, TRAN_DATE, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, VALUE_DATE, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, CHQ_NUM, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, TRAN_DESC, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, ACCT_CURR_CODE, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, DEBIT_AMT, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, CREDIT_AMT, Element.ALIGN_LEFT, 1, smallNormal,false,true);
insertCell(table, BAL_AMT, Element.ALIGN_LEFT, 1, smallNormal,false,true);
}
}
doc.add(table);
}
doc.close();
System.out.println("Done");
logger.info("Value Inserted SucessFully");
}
catch (DocumentException dex)
{
dex.printStackTrace();
doc.close();
}
catch (Exception ex)
{
ex.printStackTrace();
doc.close();
}
finally
{
if (doc != null){
//close the document
doc.close();
}
if (docWriter != null){
//close the writer
docWriter.close();
}
}
sDOCAddXML = objDmsOper.AddDocument(serverPath "/TemplateGeneration/generatedTemplates/" workitemName "/"
templateName ".pdf",
"N", workitemName, "pdf", prop, templateName);
}
}
catch (Exception e) {
sDOCAddXML = "<Record><ErrorCode>1</ErrorCode><ErrorDesc>Error in generating the template. Contact to Bank BPM Team 1.</ErrorDesc>.</Record>";
logger.info("Exception in doPost : " e.toString());
logger.info(" Inside catch---for Template Generation");
}
return sDOCAddXML;
}
private void insertCell(PdfPTable table, String text, int align, int colspan, Font font, boolean Header,boolean border){
//create a new cell with the specified Text and Font
PdfPCell cell = new PdfPCell(new Phrase(text.trim(), font));
//set the cell alignment
cell.setHorizontalAlignment(align);
//set the cell column span in case you want to merge two or more cells
cell.setColspan(colspan);
if(Header)
{
cell.setBackgroundColor(new BaseColor(112,155,21));
}
if(!border)
{
cell.setBorder(Rectangle.NO_BORDER);
}
//logger.info("base color : " BaseColor.GREEN);
//in case there is no text and you wan to create an empty row
if(text.trim().equalsIgnoreCase("")){
cell.setMinimumHeight(10f);
}
//add the call to the table
table.addCell(cell);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i ) {
paragraph.add(new Paragraph(" "));
}
}
}
**
public class HeaderFooterPageEvent extends PdfPageEventHelper {
Font bfBold12 = new Font(FontFamily.TIMES_ROMAN, 9, Font.BOLD, new BaseColor(0, 0, 0));
Font bf12 = new Font(FontFamily.TIMES_ROMAN, 8);
Font bfnormal12 = new Font(FontFamily.TIMES_ROMAN, 9);
private String name ="";
private String City ="";
private String Country ="";
private String POBOX ="";
private String PC ="";
private String initiatedby ="";
private String wi_name ="";
private String sAccountNo="";
private int TotalPages =1;
private String sCurrentDate ="";
public HeaderFooterPageEvent(String name,String POBOX, String PC,String City,String Country, String initiatedby, String wi_name,String sAccountNo,int TotalPages,String sCurrentDate)
{
this.name= name;
this.City = City;
this.initiatedby = initiatedby;
this.wi_name=wi_name;
this.POBOX=POBOX;
this.PC = PC;
this.Country = Country;
this.TotalPages=TotalPages;
this.sAccountNo=sAccountNo;
this.sCurrentDate=sCurrentDate;
}
public void onStartPage(PdfWriter writer,Document document) {
Rectangle rect = writer.getBoxSize("art");
String img = System.getProperty("user.dir") "\TemplateGeneration\dhofar_logo.jpg";
Console.log("Path IS :: " img);
Image image;
try {
image = Image.getInstance(img);
image.setAlignment(Element.ALIGN_RIGHT);
image.setAbsolutePosition(rect.getRight()-60,rect.getTop()-120);
image.scalePercent(40f, 28f);
writer.getDirectContent().addImage(image, true);
} catch (Exception e) {
Console.log("Some Error : " e);
}
Chunk chunk1 = new Chunk("Account Name t:t ",bfBold12);
Chunk chunk2 = new Chunk(this.name,bfnormal12);
Phrase p = new Phrase();
p.add(chunk1); p.add(chunk2);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT , p, rect.getLeft() 20, rect.getTop()-120,0);
chunk1 = new Chunk("Account Number t:t ",bfBold12);
chunk2 = new Chunk(this.sAccountNo, bfnormal12);
p = new Phrase();
p.add(chunk1); p.add(chunk2);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT , p, rect.getLeft() 20, rect.getTop()-140,0);
chunk1 = new Chunk("PO BOX : ",bfBold12);
chunk2 = new Chunk(this.POBOX, bfnormal12);
p = new Phrase();
p.add(chunk1); p.add(chunk2);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT , p, rect.getLeft() 20, rect.getTop()-155,0);
chunk1 = new Chunk("Postal Code : ",bfBold12);
chunk2 = new Chunk(this.PC, bfnormal12);
p = new Phrase();
p.add(chunk1); p.add(chunk2);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT , p, rect.getLeft() 20, rect.getTop()-165,0);
chunk1 = new Chunk("City : ",bfBold12);
chunk2 = new Chunk(this.City, bfnormal12);
p = new Phrase();
p.add(chunk1); p.add(chunk2);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT , p, rect.getLeft() 20, rect.getTop()-175,0);
chunk2 = new Chunk(this.Country, bfnormal12);
p = new Phrase();
p.add(chunk2);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT , p, rect.getLeft() 20, rect.getTop()-185,0);
}
public void onEndPage(PdfWriter writer,Document document) {
Rectangle rect = writer.getBoxSize("art");
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT, new Phrase(this.initiatedby "-" sCurrentDate,bfnormal12), rect.getLeft() 20, rect.getBottom() 20, 0);
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(String.format("Page %s of " this.TotalPages, writer.getPageNumber()),bf12),
rect.getRight()/2, rect.getBottom() 20, 0);
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_RIGHT , new Phrase(this.wi_name,bf12), rect.getRight()-20, rect.getBottom() 20,0);
}
}
**
Я искал решения в Интернете, но не смог найти ни одного. Также я не получаю никаких ошибок при генерации PDF-файла. Это то, что создаются только пустые страницы, когда данные превышают более 1 страницы. Буду рад вашим отзывам или любому решению, которое может помочь.
Комментарии:
1. Если это работает на вашем локальном компьютере и дает сбой только на сервере, вам следует сравнить ваш локальный компьютер и сервер, например, в отношении версий. Сетевые среды выполнения, установленные библиотеки, разрешения на доступ к ресурсам,…