how can we generate wsu:Id in soap request xml using java - soap

Please advise how can we generate dynamic wsu:Id in soap request xml.
<wsu:Timestamp wsu:Id="TS-C68ABF4EC1E628F5B5143638245038886955">
<wsu:Created>2015-07-08T19:07:30.388Z</wsu:Created>
<wsu:Expires>2015-07-08T19:12:30.388Z</wsu:Expires>
</wsu:Timestamp>
Java code :
private Element addTimestamp(Element wsSecurityHeaderElement)
throws SOAPException, DatatypeConfigurationException {
/if (false == this.addTimestamp) {
return null;
}/
Document document = wsSecurityHeaderElement.getOwnerDocument();
Element timestampElement = document.createElementNS(WSU_NAMESPACE,
"wsu:Timestamp");
timestampElement.setAttributeNS(WSU_NAMESPACE, "wsu:Id", "TS");
// hard coded ts needs to be removed
Attr idAttr = timestampElement.getAttributeNodeNS(WSU_NAMESPACE, "Id");
timestampElement.setIdAttributeNode(idAttr, true);
Element createdElement = document.createElementNS(WSU_NAMESPACE,
"wsu:Created");
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
GregorianCalendar gregorianCalendar = new GregorianCalendar();
Date now = new Date();
gregorianCalendar.setTime(now);
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("UTC"));
XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory
.newXMLGregorianCalendar(gregorianCalendar);
createdElement.setTextContent(xmlGregorianCalendar.toXMLFormat());
timestampElement.appendChild(createdElement);
Element expiresElement = document.createElementNS(WSU_NAMESPACE,
"wsu:Expires");
Date expiresDate = new Date(now.getTime() + 1000 * 60 * 5);
gregorianCalendar.setTime(expiresDate);
xmlGregorianCalendar = datatypeFactory
.newXMLGregorianCalendar(gregorianCalendar);
expiresElement.setTextContent(xmlGregorianCalendar.toXMLFormat());
timestampElement.appendChild(expiresElement);
wsSecurityHeaderElement.appendChild(timestampElement);
return timestampElement;
} </code>

Related

World map not dispalyed in crystal reports

I'm generating a pdf report using crystal report, I would like to use Data Map Tool
In c# code I've a dataset containing geographicals fields and some values to display in the map.
public class CrystalReportViewerPlugIn : ICrystalReportViewer
{
private ReportDocument _reportDocument;
private CrystalReportViewer _crystalReportViewer;
public void Init(string fileName, DataSet dataSet)
{
_reportDocument = new ReportDocument();
_reportDocument.Load(fileName);
_reportDocument.SetDataSource(dataSet);
_crystalReportViewer = new CrystalReportViewer();
_crystalReportViewer.DisplayToolbar = false;
_crystalReportViewer.DisplayGroupTree = false;
_crystalReportViewer.PageToTreeRatio = 4;
_crystalReportViewer.RefreshReport();
_crystalReportViewer.ReportSource = _reportDocument;
}
}
Then I export the result into a strem:
public MemoryStream GetCrystalReportResults(string rptFileName, DataSet ds)
{
var crystalReportViewer = new CrystalReportViewerPlugIn();
crystalReportViewer.PlugIn.Init(rptFileName, ds);
crystalReportViewer.PlugIn.Control.Visible = true;
var oStream = crystalReportViewer.PlugIn.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
var byteArray = new byte[oStream.Length];
oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
return new MemoryStream(byteArray);
}
The stream is exported as pdf:
protected virtual IHttpActionResult FinalizeExport(MemoryStream data, string name)
{
string contentType = "application/octet-stream";
name = name.GetCleanFileName();
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(data);
response.Content.Headers.Remove("content-type");
response.Content.Headers.Add("content-type", contentType);
response.Content.Headers.Remove("x-filename");
response.Content.Headers.Add("x-filename", name);
response.Content.Headers.Add("Content-Disposition", "inline; filename=\"" + name + "\"");
response.Content.Headers.Add("Content-Length", data.Length.ToString());
return ResponseMessage(response);
}
The world map is not displayed, do you have anny idea about this issue ?
Crystal report's map works only in 32 bits environment.

Copying fields in iTextSharp 5.4.5.0

I was under the impression that it is now possible to copy AcroFields using PdfCopy. In the release notes for iText 5.4.4.0 this is listed as possible now. However, when I try to do so it appears all the annotations (I think I am using that term correctly, still fairly new to iText...) for the fields are stripped out. It looks like the fields are there (meaning I can see the blue boxes that indicate an editable field), but they are not editable. If I try to bring the PDF up in Acrobat I get a message saying that "there are no fields, would you like Acrobat to discover them?" and most are found and marked and fields properly (check boxes aren't, but the text fields are).
I assume there is an additional step somewhere along the lines to re-add the annotations to the PdfCopy object, but I do not see a way to get the annotations from the PdfReader. I also cannot seem to find any documentation on how to do this (since AcroFields were for so long not supported in PdfCopy most of what I find is along that vein).
Due to sensitivity I cannot provide a copy of the PDF's in question, but using an altered version of a test program used earlier you can see the issue with the following code. It should generate a table with some check boxes in the four right columns. If I use the exact same code with PdfCopyFields in the MergePdfs method instead of PdfCopy it works as expected. This code does not produce any text fields, but in my main project they are part of the original parent PDF that is used as a template.
(Sorry for the long example, it has been cherry picked from a much larger application. You will need a PDF with a field named "TableStartPosition" somewhere in it and update RunTest with the correct paths for your local machine to get this to work.)
Has the PdfCopy functionality not made it into iTextSharp yet? I am using version 5.4.5.0.
class Program
{
Stream _pdfTemplateStream;
MemoryStream _pdfResultStream;
PdfReader _pdfTemplateReader;
PdfStamper _pdfResultStamper;
static void Main(string[] args)
{
Program p = new Program();
try
{
p.RunTest();
}
catch (Exception f)
{
Console.WriteLine(f.Message);
Console.ReadLine();
}
}
internal void RunTest()
{
FileStream fs = File.OpenRead(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\CoverPage.pdf");
_pdfTemplateStream = fs;
_pdfResultStream = new MemoryStream();
//PDFTemplateStream = new FileStream(_templatePath, FileMode.Open);
_pdfTemplateReader = new PdfReader(_pdfTemplateStream);
_pdfResultStamper = new PdfStamper(_pdfTemplateReader, _pdfResultStream);
#region setup objects
List<CustomCategory> Categories = new List<CustomCategory>();
CustomCategory c1 = new CustomCategory();
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
c1.CategorySizesInUse.Add(CustomCategory.AvailableSizes[2]);
Categories.Add(c1);
CustomCategory c2 = new CustomCategory();
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[0]);
c2.CategorySizesInUse.Add(CustomCategory.AvailableSizes[1]);
Categories.Add(c2);
List<CustomObject> Items = new List<CustomObject>();
CustomObject co1 = new CustomObject();
co1.Category = c1;
co1.Title = "Object 1";
Items.Add(co1);
CustomObject co2 = new CustomObject();
co2.Category = c2;
co2.Title = "Object 2";
Items.Add(co2);
#endregion
FillCoverPage(Items);
_pdfResultStamper.Close();
_pdfTemplateReader.Close();
List<MemoryStream> pdfStreams = new List<MemoryStream>();
pdfStreams.Add(new MemoryStream(_pdfResultStream.ToArray()));
MergePdfs(#"C:\temp\a\RenameFieldTest\RenameFieldTest\Library\Outfile.pdf", pdfStreams);
_pdfResultStream.Dispose();
_pdfTemplateStream.Dispose();
}
internal void FillCoverPage(List<CustomObject> Items)
{
//Before we start we need to figure out where to start adding the table
var fieldPositions = _pdfResultStamper.AcroFields.GetFieldPositions("TableStartPosition");
if (fieldPositions == null)
{ throw new Exception("Could not find the TableStartPosition field. Unable to determine point of origin for the table!"); }
_pdfResultStamper.AcroFields.RemoveField("TableStartPosition");
var fieldPosition = fieldPositions[0];
// Get the position of the field
var targetPosition = fieldPosition.position;
//First, get all the available card sizes
List<string> availableSizes = CustomCategory.AvailableSizes;
//Generate a table with the number of available card sizes + 1 for the device name
PdfPTable table = new PdfPTable(availableSizes.Count + 1);
float[] columnWidth = new float[availableSizes.Count + 1];
for (int y = 0; y < columnWidth.Length; y++)
{
if (y == 0)
{ columnWidth[y] = 320; }
else
{ columnWidth[y] = 120; }
}
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
PdfContentByte canvas;
List<PdfFormField> checkboxes = new List<PdfFormField>();
//Build the header row
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
//Insert the global check boxes
PdfPCell[] globalRow = new PdfPCell[availableSizes.Count + 1];
Phrase tPhrase = new Phrase("Select/Unselect All");
PdfPCell tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
tCell.AddElement(tPhrase);
globalRow[0] = tCell;
for (int x = 0; x < availableSizes.Count; x++)
{
tCell = new PdfPCell();
tCell.BackgroundColor = BaseColor.LIGHT_GRAY;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.Global.chk{0}", availableSizes[x].Replace(".", ""));
//f.FieldName = fieldName;
string js = string.Format("hideAll(event.target, '{0}');", availableSizes[x].Replace(".", ""));
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
globalRow[x + 1] = tCell;
checkboxes.Add(f);
}
table.Rows.Add(new PdfPRow(globalRow));
int status = 0;
int pageNum = 1;
for (int itemIndex = 0; itemIndex < Items.Count; itemIndex++)
{
tCell = new PdfPCell();
Phrase p = new Phrase(Items[itemIndex].Title);
tCell.AddElement(p);
tCell.HorizontalAlignment = Element.ALIGN_LEFT;
PdfPCell[] cells = new PdfPCell[availableSizes.Count + 1];
cells[0] = tCell;
for (int availCardSizeIndex = 0; availCardSizeIndex < availableSizes.Count; availCardSizeIndex++)
{
if (Items[itemIndex].Category.CategorySizesInUse.Contains(availableSizes[availCardSizeIndex]))
{
string str = availableSizes[availCardSizeIndex];
tCell = new PdfPCell();
tCell.PaddingLeft = 10f;
tCell.PaddingRight = 10f;
cells[availCardSizeIndex + 1] = tCell;
cells[availCardSizeIndex].HorizontalAlignment = Element.ALIGN_CENTER;
PdfFormField f = PdfFormField.CreateCheckBox(_pdfResultStamper.Writer);
string fieldName = string.Format("InkSaver.chk{0}.{1}", availableSizes[availCardSizeIndex].Replace(".", ""), itemIndex + 1);
//f.FieldName = fieldName; <-- This causes the checkbox to be double-named (i.e. InkSaver.Global.chk0.InkSaver.Global.chk0
string js = string.Format("hideCardSize(event.target, {0}, '{1}');", itemIndex + 1, availableSizes[availCardSizeIndex]);
f.Action = PdfAction.JavaScript(js, _pdfResultStamper.Writer);
tCell.CellEvent = new ChildFieldEvent(_pdfResultStamper.Writer, f, fieldName);
checkboxes.Add(f);
}
else
{
//Add a blank cell
tCell = new PdfPCell();
cells[availCardSizeIndex + 1] = tCell;
}
}
//Test if the column text will fit
table.Rows.Add(new PdfPRow(cells));
canvas = _pdfResultStamper.GetUnderContent(pageNum);
ColumnText ct2 = new ColumnText(canvas);
ct2.AddElement(new PdfPTable(table));
ct2.Alignment = Element.ALIGN_LEFT;
ct2.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
status = ct2.Go(true);
if ((status != ColumnText.NO_MORE_TEXT) || (itemIndex == (Items.Count - 1)))
{
ColumnText ct3 = new ColumnText(canvas);
ct3.AddElement(table);
ct3.Alignment = Element.ALIGN_LEFT;
ct3.SetSimpleColumn(targetPosition.Left, 0, targetPosition.Right, targetPosition.Top, 0, 0);
ct3.Go();
foreach (PdfFormField f in checkboxes)
{
_pdfResultStamper.AddAnnotation(f, pageNum);
}
checkboxes.Clear();
if (itemIndex < (Items.Count - 1))
{
pageNum++;
_pdfResultStamper.InsertPage(pageNum, _pdfTemplateReader.GetPageSize(1));
table = new PdfPTable(availableSizes.Count + 1);
table.SetTotalWidth(columnWidth);
table.WidthPercentage = 100;
table.Rows.Add(new PdfPRow(this.GetTableHeaderRow(availableSizes)));
}
}
}
}
private PdfPCell[] GetTableHeaderRow(List<string> AvailableSizes)
{
PdfPCell[] sizeHeaders = new PdfPCell[AvailableSizes.Count + 1];
Phrase devName = new Phrase("Device Name");
PdfPCell deviceHeader = new PdfPCell(devName);
deviceHeader.HorizontalAlignment = Element.ALIGN_CENTER;
deviceHeader.BackgroundColor = BaseColor.GRAY;
sizeHeaders[0] = deviceHeader;
for (int x = 0; x < AvailableSizes.Count; x++)
{
PdfPCell hCell = new PdfPCell(new Phrase(AvailableSizes[x]));
hCell.HorizontalAlignment = Element.ALIGN_CENTER;
hCell.BackgroundColor = BaseColor.GRAY;
sizeHeaders[x + 1] = hCell;
}
return sizeHeaders;
}
public void MergePdfs(string filePath, List<MemoryStream> pdfStreams)
{
//Create output stream
FileStream outStream = new FileStream(filePath, FileMode.Create);
Document document = null;
if (pdfStreams.Count > 0)
{
try
{
int PageCounter = 0;
//Create Main reader
PdfReader reader = new PdfReader(pdfStreams[0]);
PageCounter = reader.NumberOfPages;//This is if we have multiple pages in the cover page, we need to adjust the offset.
//rename fields in the PDF. This is required because PDF's cannot have more than one field with the same name
RenameFields(reader, PageCounter++);
//Create Main Doc
document = new Document(reader.GetPageSizeWithRotation(1));
//Create main writer
PdfCopy Writer = new PdfCopy(document, outStream);
//PdfCopyFields Writer = new PdfCopyFields(outStream);
//Open document for writing
document.Open();
////Add pages
Writer.AddDocument(reader);
//For each additional pdf after first combine them into main document
foreach (var PdfStream in pdfStreams.Skip(1))
{
PdfReader reader2 = new PdfReader(PdfStream);
//rename PDF fields
RenameFields(reader2, PageCounter++);
// Add content
Writer.AddDocument(reader);
}
//Writer.AddJavaScript(PostProcessing.GetSuperscriptJavaScript());
Writer.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (document != null)
document.Close();
foreach (var Strm in pdfStreams)
{
try { if (null != Strm) Strm.Dispose(); }
catch { }
}
//pdfStamper.Close();
outStream.Close();
}
}
}
private void RenameFields(PdfReader reader, int PageNum)
{
int tempPageNum = 1;
//rename all fields
foreach (string field in reader.AcroFields.Fields.Keys)
{
if (((reader.AcroFields.GetFieldType(field) == 1) || (reader.AcroFields.GetFieldType(field) == 2)) && (field.StartsWith("InkSaver")))
{
//This is a InkSaver button, set the name so its subclassed
string classPath;
if (reader.AcroFields.GetFieldType(field) == 2)
{
classPath = field.Substring(0, field.LastIndexOf("."));
if (field.StartsWith("InkSaver.chk"))
{
int a = field.LastIndexOf(".");
string sub = field.Substring(a + 1, (field.Length - a - 1));
int pageNum = int.Parse(sub);
int realPageNum = pageNum + tempPageNum;//PostProcessing.Instance.CoverPageLength;
PageNum = realPageNum;
}
}
else
{
classPath = field.Substring(0, field.LastIndexOf("."));
}
string newID = classPath + ".page" + PageNum.ToString();
bool ret = reader.AcroFields.RenameField(field, newID);
}
else
{
reader.AcroFields.RenameField(field, field + "_" + PageNum.ToString());// field + Guid.NewGuid().ToString("N"));
}
}
}
}
public class ChildFieldEvent : IPdfPCellEvent
{
protected PdfWriter writer;
protected PdfFormField parent;
protected string checkBoxName;
internal ChildFieldEvent(PdfWriter writer, PdfFormField parent, string CheckBoxName)
{
this.writer = writer;
this.parent = parent;
this.checkBoxName = CheckBoxName;
}
public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] cb)
{
createCheckboxField(rect);
}
private void createCheckboxField(Rectangle rect)
{
RadioCheckField bt = new RadioCheckField(this.writer, rect, this.checkBoxName, "Yes");
bt.CheckType = RadioCheckField.TYPE_SQUARE;
bt.Checked = true;
this.parent.AddKid(bt.CheckField);
}
}
internal class CustomCategory
{
internal static List<string> AvailableSizes
{
get
{
List<string> retVal = new List<string>();
retVal.Add("1");
retVal.Add("2");
retVal.Add("3");
retVal.Add("4");
return retVal;
}
}
internal CustomCategory()
{
CategorySizesInUse = new List<string>();
}
internal List<string> CategorySizesInUse { get; set; }
}
internal class CustomObject
{
internal string Title { get; set; }
internal CustomCategory Category { get;set; }
}
Please take a look at the MergeForms example. Your example is too long for me to read, but at first sight, I'm missing the following line:
copy.setMergeFields();
By the way, in MergeForms2, the fields are also renamed before the form is merged.

CellTable with Date Column

I am trying to build a CellTable Widget for time tracking. The first Column must represent all days for current month in following form
Fri, 1
Sat, 2
Sun, 3
Mon, 4
Tue, 5
…
etc. till the end of the month (28 -31 rows).
My code looks like that:
Column<Rec,String> dayColumn = new Column<Rec,String>(new TextCell())
{
#Override
public String getValue(Rec rec)
{
dayNr = DateTimeFormat.getFormat( "EE,d" ).format(new Date());
return dayNr;
}
};
table.addColumn(dayColumn, "Date");
So can I see in this Column only Today-date in all cells.
How can I get all days of the month (1...28/30/31) in this Column each in its own cell?
It would be ideal if you prepared the list of Rec items with a Date variable.
Declaring a Rec pojo with date
Class Rec{
Date date;
//getter and setters.
}
Populate list of Rec items
List<Rec> recItems = new ArrayList<Rec>();
Date now = new Date();
int nowMonth = now.getMonth();
int nowYear = now.getYear();
List<Date> listOfDatesInThisMonth = new ArrayList<Date>();
Date beginningOfMonth = new Date(nowYear,nowMonth,1);
Date beginningOfNextMonth = new Date(nowYear,nowMonth+1,1);
Date start = beginningOfMonth;
while(start.before(beginningOfNextMonth)){
listOfDatesInThisMonth.add(start);
start = new Date(nowYear,nowMonth,start.getDate()+1);
}
for(Date date:listOfDatesInThisMonth){
Rec recItem = new Rec();
recItem.setDate(date);
recItems.add(recItem );
}
Rendering
Column<Rec,String> dayColumn = new Column<Rec,String>(new TextCell())
{
#Override
public String getValue(Rec rec)
{
dayNr = DateTimeFormat.getFormat( "EE,d" ).format(rec.getDate());
return dayNr;
}
};
Something like this ??
private static String getMonthsString() {
StringBuffer buffer = new StringBuffer();
Date date = new Date() ;
int i = date.getMonth();
if(i==2)//feb {
for (int j = 0; j < 28; j++) {
buffer.append(DateTimeFormat.getFormat( "EE,d" ).format( new Date(new Date().getTime() + ((1000 * 60 * 60 * 24*j)))));
}
return buffer.toString();
}
In a Cell Table each row is one record. A month will have atleast 28 days. So you must build atleast 28 records and do setList or setData on the cell Table. A short code snippet is given below -
Date currentDate = new Date();
Map<Integer, String> daysMap = new HashMap<Integer, String>();
daysMap .put(0,"Sunday");
.
.
daysMap .put(6, "Saturday");
Map<Integer, Integer> monthMap = new HashMap<Integer, Integer>();
monthMap.put(0, 31);
.
.
monthMap.put(0, 31);
List<Rec> list = new ArrayList<Rec>();
for(int i=1;i <= monthMap.get(currentDate.getMonth());i++)
{
list.add(new Rec( daysMap.get(currentDate.getDay())+" , "+ i ));
}
Column<Rec,String> dayColumn = new Column<Rec,String>(new TextCell())
{
#Override
public String getValue(Rec rec)
{
return rec.getDayDateString(); // which returns Friday, 1 etc.
}
};
table.addColumn(dayColumn, "Date");
ListDataProvider<Rec> listDataProvider = new ListDataProvider<Rec>();
listDataProvider.addDataDisplay(table);
listDataProvider.setList( list );
You could get the dates of each month on the server side using java.util.Calendar
Showing a scrollable list for dates is horrible usability. I would suggest using a DatePickerCell instead. It uses a date picker, so that the user can just click on the date to choose it.

Horizontal wise add PdfPTable with MultiColumnText in iText

I've a pdf report generated with iText containing a PdfPTable added to MultiColumnText, sometimes becomes so large that it will be split on more than one page.
Currently the MultiColumnText has been divided by two columns and MultiColumnText fills the PdfPTable vertically Like:
Page-1
+--+--+
|T1|T5|
+--+--+
|T2|T6|
+--+--+
|T3|T7|
+--+--+
|T4|T8|
+--+--+
Page-2
+---+---+
|T9 |T13|
+---+---+
|T10|T14|
+---+---+
|T11|T15|
+---+---+
|T12|T16|
+---+---+
....I want to make this:
Page-1
+--+--+
|T1|T2|
+--+--+
|T3|T4|
+--+--+
|T5|T6|
+--+--+
|T7|T8|
+--+--+
Page-2
+---+---+
|T9 |T10|
+---+---+
|T11|T12|
+---+---+
|T13|T14|
+---+---+
|T15|T16|
+---+---+
The code is:
/**
* Initializes the fonts and collections.
* Creates a PDF document.
*
* #param from as a Date
* #param to as a Date
* #param weeklyComplianceMap as a Map for print weekly compliance
* #param monthlyComplianceMap as a Map for print monthly compliance
* #param calLogList as a List for calculate the add event
* #param locale Locale in case you want to create a Calendar in another language
* #throws DocumentException, IOException, ParseException
* #return ByteArrayOutputStream of PDF output
*/
public ByteArrayOutputStream createPdf(Date from, Date to, Map<String, Integer> weeklyComplianceMap,
Map<String, Double> monthlyComplianceMap, List<InjectionLogInfo> calLogList, Locale locale)
throws DocumentException, ParseException, IOException {
calendar = new GregorianCalendar();
calendar.setTime(from);
BaseFont bf_normal = BaseFont.createFont(
"C:/Windows/Fonts/arial.ttf", BaseFont.WINANSI,
BaseFont.EMBEDDED);
small = new Font(bf_normal, 8);
normal = new Font(bf_normal, 11);
BaseFont bf_bold = BaseFont.createFont(
"C:/Windows/Fonts/arialbd.ttf", BaseFont.WINANSI,
BaseFont.EMBEDDED);
smallBold = new Font(bf_bold, 10);
normalBold = new Font(bf_bold, 12);
bigBold = new Font(bf_bold, 14);
document = new Document(PageSize.A4, 20, 20, 40, 30);
baos = new ByteArrayOutputStream();
writer = PdfWriter.getInstance(document, baos);
ResourceBundle rb = ResourceBundle.getBundle("com.resources.messages", locale);
Paragraph hText = new Paragraph(rb.getString("lbl.calendar.view"), bigBold);
hText.setAlignment(Element.ALIGN_CENTER);
Chunk c1 = new Chunk(rb.getString("lbl.document.generated") + " ", normal);
Chunk c2 = new Chunk(fdf.format(new Date()), normal);
Chunk c3 = new Chunk(" " + rb.getString("lbl.at") + " ", normal);
Chunk c4 = new Chunk(tdf.format(new Date()), normal);
Chunk c5 = new Chunk(new VerticalPositionMark(), 500f, false);
Chunk c6 = new Chunk(rb.getString("lbl.page") + " ", normal);
Phrase fText = new Phrase();
fText.add(c1);fText.add(c2);fText.add(c3);
fText.add(c4);fText.add(c5);fText.add(c6);
HeaderFooter header = new HeaderFooter(hText, false);
HeaderFooter footer = new HeaderFooter(fText, true);
document.setHeader(header);
document.setFooter(footer);
document.open();
document.leftMargin();
mct = new MultiColumnText();
mct.addRegularColumns(document.left(), document.right(), 20, 2);
mct.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
for (int month = 0; month < monthsBetween(from, to, Calendar.MONTH); month++) {
// create a table with 8 columns
float[] colsWidth = {35f, 35f, 35f, 35f, 35f, 35f, 35f, 50f};
table = new PdfPTable(colsWidth);
table.setWidthPercentage(100);
// add the name of the month
table.getDefaultCell().setBackgroundColor(Color.WHITE);
table.addCell(getMonthCell(calendar, locale));
Double monAdh = monthlyComplianceMap.get(mdf.format(calendar.getTime()));
table.addCell(getMonthlyAdherence(monAdherence));
// add the name of the days
String[] days = getDayNames();
for (String day : days) {
table.addCell(getDayNamesCell(day, locale));
}
int day = 1;
int position = 2;
int dayofWeek = calendar.get(Calendar.DAY_OF_WEEK);
int daysinMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
// add empty cells
int rc = 0;
while (position != dayofWeek) {
rc++;
position = (position % 7) + 1;
table.addCell("");
}
// add cells for each day
while (day <= daysinMonth) {
calendar = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), day++);
table.addCell(getDayCell(calLogList, calendar, locale));
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
rc++;
String week = (calendar.get(Calendar.WEEK_OF_YEAR)-1) + ", " + calendar.get(Calendar.YEAR);
if (null != weeklyComplianceMap) {
wa = weeklyComplianceMap.get(week);
table.addCell(getDayAdherenceCell(weekAdherence));
} else {
String weekAdherence = "0%";
table.addCell(getDayAdherenceCell(weekAdherence));
}
}
}
if (9 < rc)
table.setSpacingAfter(20);
else
table.setSpacingAfter(40);
// complete the table
table.completeRow();
// add the table to MultiColumnText object
mct.addElement(table);
// increment the day by 1
calendar.add(Calendar.DATE, 1);
}
document.add(mct);
document.newPage();
document.close();
return baos;
}
/**
* Creates a PdfPCell with the name of the month
*
* #param calendar a date
* #param locale a locale
* #return a PdfPCell with rowspan 7, containing the name of the month
*/
public PdfPCell getMonthCell(Calendar calendar, Locale locale) {
PdfPCell cell = new PdfPCell();
cell.setColspan(7);
cell.setMinimumHeight(30);
cell.setBackgroundColor(Color.GRAY);
Paragraph p = new Paragraph(String.format(locale, "%1$tB %1$tY", calendar), normalBold);
p.setAlignment(Element.ALIGN_LEFT);
cell.addElement(p);
return cell;
}
/**
* Creates a PdfPCell for a month
*
* #param string adherence of a month
* #return a PdfPCell
*/
private PdfPCell getMonthlyAdherence(String adherence) {
PdfPCell cell = new PdfPCell();
cell.setMinimumHeight(35);
//cell.setBorderColorLeft(Color.GRAY);
cell.setBackgroundColor(Color.GRAY);
Paragraph p = new Paragraph(adherence, smallBold);
p.setAlignment(Element.ALIGN_RIGHT);
cell.addElement(p);
return cell;
}
/**
* Creates a PdfPCell with the name of the day
*
* #param day name of a day
* #param locale a locale
* #return a PdfPCell, containing the name of the day
*/
public PdfPCell getDayNamesCell(String day, Locale locale) {
PdfPCell cell = new PdfPCell();
cell.setPadding(3);
cell.setBackgroundColor(Color.LIGHT_GRAY);
Paragraph p = new Paragraph(day, smallBold);
p.setAlignment(Element.ALIGN_CENTER);
cell.addElement(p);
return cell;
}
/**
* Creates a PdfPCell for a specific day
*
* #param calendar a date
* #param locale a locale
* #return a PdfPCell
*/
public PdfPCell getDayCell(List<InjectionLogInfo> calLogList, Calendar calendar, Locale locale) {
PdfPCell cell = new PdfPCell();
cell.setPadding(3);
// set the content in the language of the locale
Chunk chunk = new Chunk(String.format(locale, "%1$te", calendar), small);
// a paragraph with the day
Paragraph p = new Paragraph(chunk);
p.setAlignment(Element.ALIGN_CENTER);
cell.addElement(p);
return cell;
}
/**
* Creates a PdfPCell for a week
*
* #param string adherence of a week
* #return a PdfPCell
*/
public PdfPCell getDayAdherenceCell(String adherence) {
PdfPCell cell = new PdfPCell();
cell.setPadding(3);
// set the adherence for each week
Chunk chunk = new Chunk(adherence, small);
// a paragraph with the adherence
Paragraph p = new Paragraph(chunk);
p.setAlignment(Element.ALIGN_CENTER);
cell.addElement(p);
return cell;
}
/**
* Retrieves a Day Names for a single week
*
* #return a String array of day names
*/
public String[] getDayNames() {
DateFormatSymbols symbols = new DateFormatSymbols();
String[] dayNames = symbols.getShortWeekdays();
List<String> stringList = new ArrayList<String>();
for (String string : dayNames) {
if (string != null && string.length() > 0) {
stringList.add(string);
}
}
if (stringList.size() > 0) {
String one = stringList.get(0);
stringList.remove(0);
stringList.add(one);
stringList.add("%");
}
dayNames = stringList.toArray(new String[stringList.size()]);
return dayNames;
}
I stuck with this so any help is very appreciated.
Thanks.
I think you are using new PdfPtable(1) per MultiColumnText. change it to new PdfPtable(2) to get 2 columns table per 1 MultiColumnText.

saving email attachments as binary to the database using c#

I can get email attachments from exchange server 2003 (MAPI.Attachment). How can I save the pdf attachment file as binary into the database?
Here's some code to understand better. For testing purposes I am saving the attachment pdf file into a filesystem. How ca I go about saving that into a database? Or how can I convert that into a byte array? Also, how can I get the size of the file since I need that when I declare the byte array "fileData"...
byte[] fileData = new byte[10000];
string[] fileTokens = new string[2];
string[] result = new string[3];
message.Unread = false;
emailSubject = message.Subject.ToString();
emailBody = message.Text.ToString();
MAPI.Attachments test = null;
test = (MAPI.Attachments)message.Attachments;
int attachmentCount = (int)test.Count;
for (int loopCounter = 1; loopCounter <= attachmentCount; loopCounter++)
{
MAPI.Attachment test2 = (MAPI.Attachment)test.get_Item(loopCounter);
bool temp = (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0);
if (test2.Name.ToString().Contains(".pdf") && test2.Name.ToString().IndexOf('Q') == 0)
{
//test2.ReadFromFile(fileData);
test2.WriteToFile("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
}
RequestHistorySet historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);
bool res = historySet.Update();
message.Unread = false;
message.Update();
And here's the Update function from historySet Class
public bool Update()
{
using (SqlConnection mySqlConnection = ...))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("CONNECTION STRING..", mySqlConnection);
// Set up the OriginalName parameter
SqlParameter prmId = new SqlParameter("#id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
SqlParameter prmRequsetDate = new SqlParameter("#requestDate", SqlDbType.DateTime);
prmRequsetDate.Value = requestDate;
myCommand.Parameters.Add(prmRequsetDate);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("#uplodedQuote_File ", SqlDbType.VarBinary);
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
myCommand.Parameters.Add(prmFileData);
SqlParameter prmFileExtension = new SqlParameter("#uplodedQuote_Ext", SqlDbType.NVarChar);
prmFileExtension.Value = fileExtension;
myCommand.Parameters.Add(prmFileExtension);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
return result;
}
}
As of now this is what I have done. I save it to a filesystem and then read from there.
test2.WriteToFile("d:\\data\\" + test2.Name);
fileData = FileToByteArray("d:\\data\\" + test2.Name);
PDFParser pdfParser = new PDFParser();
pdfParser.ReadPdfFile("d:\\data\\" + test2.Name, result);
TryToDelete("d:\\data\\" + test2.Name);
sentTime = (DateTime)message.TimeSent;
string fileName = (string)test2.Name;
fileTokens = fileName.Split('.');
historySet = new RequestHistorySet(1, sentTime, fileData, fileTokens[1]);