Can someone explain what are iTextEvents in ItextSharp? - events

Can someone explain what are iTextEvents in ItextSharp..
I have found a bunch of codes with its use but i dont get how they works..
Im asking you if anyone can explain me these:
OnOpenDocument
OnEndPage
OnCloseDocument

If you are looking to start using iText, then your question is obsolete. You are referring to a concept that was used in versions 5 and earlier of iText for .NET (we abandoned the name iTextSharp a long time ago). If you want to start using iText for .NET, you should start with version 7, not with iText 5 or earlier, because we stopped development on those versions. Any release we make now is nothing more than a maintenance release (maintenance releases don't contain new functionality, they have bug fixes that are meant for paying users who can't migrate to iText 7 immediately).
The name page events was misleading because those events were initially used to allow developers to execute code when a new page was created or finalized, but as the code grew organically, we also started to use the page event functionality for other things, such as: to add special behavior of a Chunk (OnGenericTag()) or to execute code before or after adding a Paragraph. That was an example of bad design.
We fixed this bad design in iText 7, where we introduced renderers and event handlers. See chapter 3 of the jump-start tutorial, entitled Using renderers and event handlers.
In iText 7, we can create an event handler such as:
protected internal class MyEventHandler : IEventHandler {
public virtual void HandleEvent(Event #event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)#event;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdfDoc.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Set background
Color limeColor = new DeviceCmyk(0.208f, 0, 0.584f, 0);
Color blueColor = new DeviceCmyk(0.445f, 0.0546f, 0, 0.0667f);
pdfCanvas.SaveState()
.SetFillColor(pageNumber % 2 == 1 ? limeColor : blueColor)
.Rectangle(pageSize.GetLeft(), pageSize.GetBottom(), pageSize.GetWidth(), pageSize.GetHeight())
.Fill()
.RestoreState();
//Add header and footer
pdfCanvas.BeginText()
.SetFontAndSize(C03E03_UFO.helvetica, 9)
.MoveText(pageSize.GetWidth() / 2 - 60, pageSize.GetTop() - 20)
.ShowText("THE TRUTH IS OUT THERE")
.MoveText(60, -pageSize.GetTop() + 30)
.ShowText(pageNumber.ToString())
.EndText();
//Add watermark
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, pdfDoc, page.GetPageSize());
canvas.SetProperty(Property.FONT_COLOR, Color.WHITE);
canvas.SetProperty(Property.FONT_SIZE, 60);
canvas.SetProperty(Property.FONT, C03E03_UFO.helveticaBold);
canvas.ShowTextAligned(new Paragraph("CONFIDENTIAL"), 298, 421, pdfDoc.GetPageNumber(page), TextAlignment.
CENTER, VerticalAlignment.MIDDLE, 45);
pdfCanvas.Release();
}
}
The event handler is introduced in the code like this:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new C03E03_UFO.MyEventHandler(this));
// Initialize document
Document document = new Document(pdf);
Paragraph p = new Paragraph("List of reported UFO sightings in 20th century").SetTextAlignment(TextAlignment
.CENTER).SetFont(helveticaBold).SetFontSize(14);
document.Add(p);
Table table = new Table(new float[] { 3, 5, 7, 4 });
table.SetWidth(UnitValue.CreatePercentValue(100));
StreamReader sr = File.OpenText(DATA);
String line = sr.ReadLine();
Process(table, line, helveticaBold, true);
while ((line = sr.ReadLine()) != null) {
Process(table, line, helvetica, false);
}
sr.Close();
document.Add(table);
document.Close();
This code adds a background, a watermark, a header, and a footer, as is shown in this figure:
Page events in "iTextSharp" had a similar purpose, but you shouldn't use them anymore. They are outdated. You should use iText 7 instead.
If you posted your question out of historical curiosity, you should search old questions on Stack Overflow, such as:
How can I add an image to all pages of my PDF?
itextsharp: How to generate a report with dynamic header in PDF using itextsharp?
Change the color of pdf pages alternatively using iText pdf in java
How to introduce multiple PdfPageEventHelper instances?
...

Related

Converting to NotificationCompat breaks SetSmallIcon functionality?

I've been having some trouble moving Notification to the Compat library version: In the main library, I used to just convert an icon to a bitmap (api 23 and up) and do SetSmallIcon(icon) to show a dynamic notification icon.
But the Compat version has only an int argument (I assume it is the resource ID), and I cannot find any information as to how to generate/convert/add my bitmap and/or icon in it.
The bitmap Is basically generated text converted into a bitmap via a canvas which show the most vital information.
My question is: Is there a way to make a class variable into a resource, or get its ID that works like a resoource ID, or some other hack that will allow me to actually add my bitmap that I create at runtime?
You can use this code. Refer the line where icon is being used
var notificationBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.NotifIconSis).SetColor(Android.Graphics.Color.Rgb(33, 150, 243))
.SetContentTitle(user.Organization)
.SetSubText(user.ModuleName).SetStyle(new NotificationCompat.BigTextStyle().BigText(user.BodyText))
.SetContentText(user.BodyText)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.Build();
var notificationManager = NotificationManagerCompat.From(Application.Context);
//var notification = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
//var mp = MediaPlayer.Create(ApplicationContext, notification);
//mp.Start();
//notificationManager.Notify(redomId, notificationBuilder);

Auto Scroll Vertical Field Manager

I have developed a BlackBerry Application with a simple chat feature. The chat messages appear inside a Vertical Field Manager (VFM) when the user clicks Send. The user can sent multiple messages. Every new message sent appears below the older message. This way, the size of the Vertical Field Manager keeps increasing. I have created a scroll-able VFM and so the user can view the latest message sent by scrolling down. Is it possible to auto-scroll to the bottom of the VFM when a message is sent so that the focus is set on the last message?
I have tried calling vfm.setVerticalScroll(int y); as well as LabelField chat1 = new LabelField( "Hi", Field.FIELD_LEFT|Field.FOCUSABLE); but this is not helping. Please guide.
vr2 = Vertical Field Manager
chat1 = Chat message added to the VFM
EDIT: I came across this link on StackOverFlow and applied changes in my code as follows:
vr2.setVerticalScroll(vr2.getVirtualHeight());
LabelField chat1 = new LabelField( "Hi", Field.FIELD_LEFT)
{
protected void applyTheme(Graphics g, boolean arg1)
{
g.setColor(Color.DEEPSKYBLUE);
super.applyTheme(g, arg1);
}
};
Font myFont = Font.getDefault().derive(Font.BOLD, 8, Ui.UNITS_pt);
chat1.setFont(myFont);
chat1.setBorder( leftBorder );
chat1.setMargin( 0, 0, -15, 0);
vr2.setBorder(bdr);
vr2.add(chat1);
Field f;
int i = vr2.getFieldCount();
f = vr2.getField(i-1); //getFieldCount, gets total number of fields
f.setFocus();
This has brought me very close to the solution I am looking for. The VFM is scrolling below fine. However, instead of positioning to the last message in the VFM, it scrolls to the second last message every time. Why is this so? It should scroll to the last message in the VFM; right at the bottom of VFM.
I finally managed to get this solved. I will share my answer in case there are others out there stuck with such an issue. While the edit in my question above helped me come closer to the solution, I figured out the mistake was in not calling vr2.setVerticalScroll(vr2.getVirtualHeight()); at the right place.
For details, please check this question on stackoverflow and this on blackberry support forums. The solution is as follows:
LabelField chat1 = new LabelField( "Hi", Field.FIELD_LEFT)
{
protected void applyTheme(Graphics g, boolean arg1)
{
g.setColor(Color.DEEPSKYBLUE);
super.applyTheme(g, arg1);
}
};
Font myFont = Font.getDefault().derive(Font.BOLD, 8, Ui.UNITS_pt);
chat1.setFont(myFont);
chat1.setBorder( leftBorder );
chat1.setMargin( 0, 0, -15, 0);
vr2.setBorder(bdr);
vr2.setVerticalScroll(vr2.getVirtualHeight()); //scrolls to the bottom of the vertical field manager
vr2.add(chat1);
Field f;
int i = vr2.getFieldCount();
f = vr2.getField(i-1); //getFieldCount, gets total number of fields
f.setFocus(); //sets focus on the newly added field

Custom live tile rendering issue on Windows Phone (7/8)

In my Windows Phone app's main page, users can click a button to do some stuff and that will trigger the live tile to update.
The problem I am having is, if the user clicks the button and then hit the phone's Back button really quickly, the live tile sometimes will not render properly. This issue rarely happens, but it does happen and when it happens it just looks bad...
The way I implement the live tile is, create a user control that looks exactly the same as the live tile and then save it to isolated storage. Then retrieve it and store it in a FliptileData object. Finally I call the Update method on the ShellTile. Please see the following piece of code to demonstrate the process.
// the function that saves the user control to isolated storage
public Uri SaveJpegToIsolatedStorage(FrameworkElement tile, string suffix, int tileWidth = 336, int tileHeight = 336)
{
var bmp = new WriteableBitmap(tileWidth, tileHeight);
// Force the content to layout itself properly
tile.Measure(new Size(tileWidth, tileHeight));
tile.Arrange(new Rect(0, 0, tileWidth, tileHeight));
bmp.Render(tile, null);
bmp.Invalidate();
// Obtain the virtual store for the application
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(IsolatedStorageFileName + suffix, FileMode.Create, myStore))
{
try
{
bmp.SaveJpeg(fileStream, tileWidth, tileHeight, 0, 100);
}
catch (Exception)
{
return null;
}
}
return new Uri("isostore:/" + IsolatedStorageFileName + suffix, UriKind.Absolute);
}
// save the user control to isolated storage and prepare the FlipTileData object
wideFrontTileImage = SaveJpegToIsolatedStorage((UserControl)this.WideFrontTile, "_wide_front", 691);
var flipTileData = new FlipTileData();
flipTileData.WideBackgroundImage = wideFrontTileImage;
return flipTileData;
// update the live tile
var shellTile = ShellTile.ActiveTiles.FirstOrDefault();
shellTile.Update(customTile.GetFlipTileData(data.UndoneMemosCount == "0" && data.TotalMemosCount == "0"));
I think the reason that's causing all this is, when the user clicks the Back button too quickly, the OS terminates all the processes running within the app and the rendering wasn't done at that time. I'm thinking if there's a way to know when the rendering is finished, so I can cancel the Back button and wait until it's finished then manually exit the app. But I simply dunno how...
Any help on this one will be greatly appreciated!
I have ran into similar issue in my WP8 app. The problem was that I was updating my Tile in ApplicationDeactivated event handler. The thing is you should not update your tiles there, but rather in your MainPage.OnNavigatedFrom override. Once I changed this, it works just fine.

Generate a pdf file and send after querying database for a pass mark

My project is almost done, and thanks to stackoverflow. Now that I have managed to capture Users details and their certificates, I am looking for a way to generate pdf which I will send to those who passed.
I am not looking for the code at the moment. I have an asp.net mvc 3 application which shows Certificates details for my students. Now I want the certificates to be generated then sent by email, all this automated.
First I would like help on how I can generate a pdf from database values and sending the generated pdf wont be a problem.
Using iTextSharp, this code will create and serve a PDF:
public FileStreamResult DownloadPDF()
{
MemoryStream workStream = new MemoryStream();
using(Document document = new Document())
{
PdfWriter.GetInstance(document, workStream).CloseStream = false;
document.Open();
document.SetPageSize(PageSize.LETTER);
document.SetMargins(12, 12, 8, 7);
document.NewPage();
// Create a new Paragraph object with the text, "Hello, World!"
var welcomeParagraph = new Paragraph("Hello, World!");
// Add the Paragraph object to the document
document.Add(welcomeParagraph);
// This is where your data would go
document.Close();
}
workStream.Position = 0;
FileStreamResult fileResult = new FileStreamResult(workStream, "application/pdf");
fileResult.FileDownloadName = "test.pdf";
return fileResult;
}
For more information see Creating PDF Documents with ASP.NET and iTextSharp
There are a lot of tutorials online, but this should get you started.

How to decrease margin programmatically on exported BIRT PDF reports?

Is there a way to decrease the margin of the PDF reports using the BIRT API?
I tried setting the PDF rendering options to:
PDFRenderOption renderOption = new PDFRenderOption();
renderOption.setOutputFormat(PDFRenderOption.OUTPUT_FORMAT_PDF);
renderOption.setOption(IPDFRenderOption.PDF_HYPHENATION, true);
renderOption.setOption(IPDFRenderOption.PDF_TEXT_WRAPPING, true);
renderOption.setOption(IPDFRenderOption.PAGE_OVERFLOW,
IPDFRenderOption.ENLARGE_PAGE_SIZE);
Basically the problem I have is that if I have a longer text in a column (from one of the tables) it will get it on the next line, but if I set the IPDFRenderOption.PDF_HYPHENATION to false I will get the text split right in the middle of the text (see below).
PDF with IPDFRenderOption.PDF_HYPHENATION set to true
PDF with IPDFRenderOption.PDF_HYPHENATION set to false
So, I was trying to set the margin of the PDF to be smaller to overcome this issue, but I don't find any documentation on how to do this with the BIRT API...
There is this suggestion of modifying the master page, but I have way too many reports to modify them by hand.
How should I approach the problem? Is this even possible using the BIRT API?
All I needed to do was to loop through all the handles, test which of them is a MasterPageHandle and call setProperty with these keys:
MasterPageHandle.BOTTOM_MARGIN_PROP
MasterPageHandle.LEFT_MARGIN_PROP
MasterPageHandle.RIGHT_MARGIN_PROP
MasterPageHandle.TOP_MARGIN_PROP
and the DimensionValue I needed.
Code sample
#SuppressWarnings("unchecked")
private void shrinkPageSizeForExport(IReportRunnable reportRunnable) {
DesignElementHandle designHandle = reportRunnable.getDesignHandle();
IElementDefn elementDefn = designHandle.getDefn();
for (int i = 0; i < elementDefn.getSlotCount(); i++) {
SlotHandle slotHandle = designHandle.getSlot(i);
for (DesignElementHandle elementHandle: (List<DesignElementHandle>)slotHandle.getContents()) {
if (!(elementHandle instanceof MasterPageHandle)) continue;
MasterPageHandle mph = (MasterPageHandle)elementHandle;
DimensionValue dv = new DimensionValue(0.1, "cm");
setAllMarginsTo(mph, dv);
}
}
}
private void setAllMarginsTo(MasterPageHandle mph, DimensionValue dv) {
try {
mph.setProperty(MasterPageHandle.BOTTOM_MARGIN_PROP, dv);
mph.setProperty(MasterPageHandle.LEFT_MARGIN_PROP, dv);
mph.setProperty(MasterPageHandle.RIGHT_MARGIN_PROP, dv);
mph.setProperty(MasterPageHandle.TOP_MARGIN_PROP, dv);
} catch (SemanticException se) {
throw new RuntimeException("Cannot set margins for report export!", se);
}
}
Alternate suggestion:
Build a MasterPage in your BIRT library, and use it on all reports. Then all reports it is used on can be updated at one time. If you did not start with library MasterPages, you can replace the report MasterPage with the library master page, quicker then trying to recode them all.
Things like DataSources, and MasterPages are almost always better as library items.

Resources