Blog Posts

Tuesday, May 25, 2010

Best fit of text length while printing PDF templates

In one of my projects we are using PDF templates for the generating the PDF files. Like we create a template first with the textboxes on it and later we can use the template with filling the dynamic data and saving the resulting file. The issue was with the dynamic data not fitting in to the textboxes when the data from database is in Capital Letters. As we were not using the mono spaced fonts like courier. Mono spaced font takes equal number of points while printing on screen or paper say 8X12 pixels for all characters it may be ‘I’ or ‘W’. But non mono spaced font will take different width for different characters to save space, like ‘I’(may be say 3 pixels) will take less width on paper or screen than ‘W’(say 12pixels). And also capital letters take more width than small case. Got it?

There are more than 10 textboxes on my PDF for a paragraph like content to show on the PDF to look like lines of running text. Initially I set the line length to some 100 characters for each line in my code like if the text to show is 400 characters I was displaying in 4 lines. My issue was it is giving space on right side of the PDF textbox when text is in small letters. Then I increased number of characters to show from 100 to 120. Then the issue was with the uppercase text it was concatenated as the textbox width on the PDF form is limited and cannot increase.

The solution is to calculate the best fit of text length at runtime instead hard coding to 100 or 120. When the text is in uppercase the length can be calculated to 90 or so. And when the text is in lower case the length can be 120 characters.

Case Study: We are using iTextSharp (an open source project from SourceForge), there is a mothod GetEffectiveStringWidth() in the PdfContentByte class. This function will calculate how many points will the text take on the PDF at runtime based on the supplied font.

Before –





GetNextLine() is my own method (read at the end if you are interested) which returns the next line to display for the supplied length to maintain the text into readable way by keeping the words to-gether as when using
Substring may split single word into lines, like 'letter' can be splitted to 'let' at the end of first line and 'ter' in second line.


PdfReader pdfformreader=new PdfReader(strPdfTempPath);
PdfStamper pdfformstamper=new PdfStamper(pdfformreader,new FileStream(strPdfNewPath,FileMode.Create));

PdfContentByte cb = pdfformstamper.GetOverContent(2);
cb.SetFontAndSize(FontFactory.GetFont("Arial").GetCalculatedBaseFont(false), 8f);
//i am printing the text strRemarksSummary in to 12 lines
for(int ind = 0 ; ind < 12 ; ind++)
{
   string strNextRemarks = PermitPdfForm.GetNextLine( ref strRemarksSummary, 125); // fixed length of 125 
   if( strNextRemarks.Equals("EndOfContent"))
   {
       break;
   }
   else
   {
       pdfformfields.SetField( "txtRemarks" + (ind+1) , strNextRemarks);
   }
}
After, instead of hard coding to 125 use
-



string strNextRemarks = PermitPdfForm.GetNextLine( ref strRemarksSummary, //125);
                        PermitPdfForm.GetEffectiveTextLength(
                        ref strRemarksSummary, cb,
cb.PdfDocument.PageSize.Width - 70)); // textbox width on the pdf

public static int GetEffectiveTextLength(
            ref string str, PdfContentByte cb, float intTextBoxWidth)
{
    int intCharIndex = 0;
    while( true)
    {
        string strTemp = str.Substring(0,intCharIndex);
        float fltLength = cb.GetEffectiveStringWidth(strTemp,false);
        if ( fltLength > intTextBoxWidth)
        {
            return intCharIndex - 1;
        }
        else
        {
            intCharIndex++;
            if( intCharIndex >= str.Length)
                return str.Length;
        }
        //set to maximum of 1000 loop only to avoid infinite loop
        if( intCharIndex > 1000)
            return str.Length;
    }
}



public static string GetNextLine(
    ref string strContent, int intLineMaxLength)
{
    if ( strContent == null ||
        strContent.Length == 0)
    {
        return "EndOfContent";
    }

    string strReturn = "";

    if( strContent.IndexOf('\n') != -1 &&
        strContent.IndexOf('\n') < intLineMaxLength)
    {
        strReturn = strContent.Substring( 0, strContent.IndexOf('\n'));
        strContent = strContent.Substring( strContent.IndexOf('\n') + 1);
        return strReturn;
    }

    if ( strContent.Length <= intLineMaxLength)
    {
        strReturn = strContent;
        strContent = "";
    }
    else
    {
        int intLastCharIndex = intLineMaxLength;
        while( true)
        {
            if ( Char.IsWhiteSpace( strContent[intLastCharIndex]))
            {
                strReturn = strContent.Substring( 0, intLastCharIndex);
                strContent = strContent.Substring( intLastCharIndex + 1).Trim();
                break;
            }
            else
            {
                intLastCharIndex--;
                if( intLastCharIndex == 0)
                {
                    strReturn = strContent.Substring( 0, intLineMaxLength);
                    strContent = strContent.Substring( intLineMaxLength + 1).Trim();
                    break;
                }
            }
        }
    }
    return strReturn;
}

Friday, May 7, 2010

SQL Server 2005 Paging – The Holy Grail


The paging and ranking functions introduced in 2005 are old news by now, but the typical ROW_NUMBER OVER() implementation only solves part of the problem.
Nearly every application that uses paging gives some indication of how many pages (or total records) are in the total result set. The challenge is to query the total number of rows, and return only the desired records with a minimum of overhead? The holy grail solution would allow you to return one page of the results and the total number of rows with no additional I/O overhead.

In theory, ROW_NUMBER() gives you all the information you need because it assigns a sequential number to every single row in your result set. It all falls down, of course, when you only return a subset of your results that don't include the highest sequential number. The solution is to return a 2nd column of sequential numbers, in the reverse order. The total number of the records will always be the sum of the two
fields on any given row minus 1 (unless one of your sequences is zero-bound).


DECLARE @startRow INT ; SET @startrow = 50
;
WITH cols AS
(
 SELECT col1, col2,
  ROW_NUMBER() OVER(ORDER BY col1, col2) AS seq,
  ROW_NUMBER() OVER(ORDER BY col1 DESC, col2 desc) AS totrows
 FROM Table1
)

SELECT col1, col2, totrows + seq -1 as TotRows
 FROM cols
 WHERE seq BETWEEN @startRow AND @startRow + 49
 ORDERBY seq


This approach gives us our page of data and the total number of rows with zero additional overhead! (well, maybe one or two ms of CPU time, but that's it).
For more info refer - http://www.sqlservercentral.com/articles/T-SQL/66030/

Wednesday, May 5, 2010

Using Silverlight Templated Control to create controls


Introduction

In one of my Silverlight projects, the requirement is to show
slide show of the pictures online and the zooming funcionality
needs to implement. I created one reusable control in
Silverlight using the 'Silverlight Templated Control' available
in Silverlight tools. Here I want to share my code for the Album
which uses the XML file to show the images from the server from
multiple folders which are mapped to the album.



Using the code

The goal is to create a Album control that is reusable in a
Silverlight project as below -


<grid x:name="LayoutRoot" />
<xamlalbum x:name="XAlbum" albumsrc="Album.xml" borderthickness="1" borderbrush="Black"
disablealbumselection="True" slideduration="3" height="500" width="600" imgsource="Babies" />
</grid />

To get the output like this -


Developing the control


Create a new 'Silverlihgt Class Library' project to create
the control, to build a .dll file to distribute the control.



Add new control of type 'Silverlight Templated Control' to
create our control.



This will create a class file for the code-behind of the
control and the Generic.xml under Theme folder which contains
the template of our control.


The following is template code which has the next and
previous buttons and other buttons for the slideshow and folder
selection. A slider control for zooming of the control,
MouseWheel event is also added on the image to zoom.



<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SLNuke">
<Style TargetType="local:XAMLAlbum">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:XAMLAlbum">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Canvas Name="root" Width="{TemplateBinding Width}"
local:Clip.ToBounds="True"
Height="{TemplateBinding Height}" Margin="0,0,0,0" >
<Canvas.Resources>
<Storyboard x:Name="SlideShow">
<ObjectAnimationUsingKeyFrames BeginTime="00:00:00" x:Name="objectSS"
Storyboard.TargetProperty="Text"
Storyboard.TargetName="txtCurrentImg">
</ObjectAnimationUsingKeyFrames>
</Storyboard>
<Style TargetType="Button" x:Name="AlbumButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="White" BorderBrush="black" BorderThickness="2">
<Canvas Background="Transparent" Width="20" Height="20"
HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Canvas.Left="6" Canvas.Top="3" HorizontalAlignment="Center" VerticalAlignment="Center"
Foreground="black" FontFamily="Arial" FontWeight="Bold" FontSize="14"
Text="{TemplateBinding Content}"></TextBlock>
</Canvas>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="Button" x:Name="SlideShowButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="White" BorderBrush="black" BorderThickness="2">
<Canvas Background="Transparent" Width="20" Height="20"
HorizontalAlignment="Center" VerticalAlignment="Center">
<Rectangle Canvas.Top="3" Canvas.Left="3" Width="14" Height="10"
Stroke="Black" StrokeThickness="1"></Rectangle>
<Line Stroke="Black" StrokeThickness="1"
X1="4" Y1="17" X2="9" Y2="13"></Line>
<Line Stroke="Black" StrokeThickness="1"
X1="16" Y1="17" X2="11" Y2="13"></Line>
</Canvas>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="Button" x:Name="SlideShowDisabledButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="White" BorderBrush="black" BorderThickness="2">
<Canvas Background="Transparent" Width="20" Height="20"
HorizontalAlignment="Center" VerticalAlignment="Center">
<Rectangle Canvas.Top="3" Canvas.Left="3" Width="14" Height="10"
Stroke="Black" StrokeThickness="1"></Rectangle>
<Line Stroke="Black" StrokeThickness="1"
X1="4" Y1="17" X2="9" Y2="13"></Line>
<Line Stroke="Black" StrokeThickness="1"
X1="16" Y1="17" X2="11" Y2="13"></Line>
<Line Stroke="Red" StrokeThickness="1"
X1="6" Y1="4" X2="13" Y2="11"></Line>
<Ellipse Canvas.Top="4" Canvas.Left="6" Width="7"
Height="7" Stroke="Red"></Ellipse>
</Canvas>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Canvas.Resources>
<Image Canvas.Left="0" Canvas.Top="0" Stretch="Uniform"
Source="{TemplateBinding ImgSource}" Name="mainImg">
<Image.RenderTransform>
<ScaleTransform x:Name="ImgScaleTransform" ScaleX="1" ScaleY="1"></ScaleTransform>
</Image.RenderTransform>
</Image>
<TextBox Name="txtCurrentImg" Text="0" Opacity="0"></TextBox>
<Button Content=">" Style="{StaticResource AlbumButtonStyle}"
Name="btnNext" Opacity="0.1" Height="20" Width="20" >
</Button>
<Button Content="&lt;" Style="{StaticResource AlbumButtonStyle}"
Name="btnPrev" Opacity="0.1" Height="20" Width="20">
</Button>
<Button Style="{StaticResource SlideShowDisabledButtonStyle}"
Name="btnSlideShow" Opacity="0.1" Height="20" Width="20">
</Button>
<Slider x:Name="sldrZoom" Orientation="Vertical" Opacity="0.2"
Height="100" Width="20"
Maximum="10" Minimum="1" Value="1"></Slider>
<Popup Name="ablumList" IsOpen="False">
<ListBox Name="lstAlbums" Margin="0,0,0,0" Padding="0,0,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock MinWidth="100" Text="{Binding}" Height="15"
Foreground="Black" FontSize="10"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Popup>
<Image Name="btnAlbums" Opacity="0.2" Height="30" Width="30"></Image>
</Canvas>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

The album source file (.xml) contains the following format,
which contains the albums (Folder) to be bound to the control
and the pictures file names, which will be copied to the
ClientBin of the project which uses the current control.


<?xml version="1.0" encoding="utf-8" ?>
<Albums>
<Album Name="Babies">
<Pic>baby1.jpg</Pic>
<Pic>baby2.jpg</Pic>
.....
</Album>
......
</Albums>

In the code-behind XAMLAlbum.cs load the above xml file by an
asynchronous call to server, which is referenced by the AlbumSrc
property to get the list of the Albums and the Picture names.
Here I am using GetTemplateChild() method to get the controls
from template at runtime



string[] arrPics;
public static readonly DependencyProperty AlbumSrcProperty =
DependencyProperty.Register("AlbumSrc", typeof(String), typeof(XAMLAlbum), null);
public string AlbumSrc
{
get { return (string)GetValue(AlbumSrcProperty); }
set { SetValue(AlbumSrcProperty, value); }
}

/// 
        /// Override the apply template handler.
        ///
        public override void OnApplyTemplate()
{
base.OnApplyTemplate();

....

SetFirstPicToImage();
}

public int CurrentImg
{
get { return (int)GetValue(CurrentImgProperty); }
set
{
SetValue(CurrentImgProperty, value);
ShowPicture();
}
}
void SetFirstPicToImage()
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
wc.OpenReadAsync(new Uri(AlbumSrc, UriKind.Relative));
}
XDocument doc;
private void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{     
return;
}
using (Stream s = e.Result)
{
//load the xml file
                doc = XDocument.Load(s);
//get the current folder name to show that is given by the user in the property ImgSourceProperty
                strFolder = (string)GetValue(ImgSourceProperty);
var pics = from p in doc.Descendants("Album")
where (string)p.Attribute("Name") == strFolder
select p;
var pic = from p in pics.Descendants("Pic")
select (string)p;
arrPics = new string[pic.Count()];
int ind = 0;
foreach (string str in pic.ToArray())
{
arrPics[ind] = str;
ind++;
}

// this will call method ShowPicture() through the property setter - 0 to show the first picture from album
                CurrentImg = 0;
//load album names to listbox
                if (GetTemplateChild("lstAlbums") != null)
{
ListBox lst = ((ListBox)GetTemplateChild("lstAlbums"));

var albums = from p in doc.Descendants("Album")
select (string)p.Attribute("Name");
lst.ItemsSource = albums.ToList();
lst.SelectedIndex = 0;
Canvas root = ((Canvas)GetTemplateChild("root"));

Popup albumList = ((Popup)GetTemplateChild("ablumList"));

double left = 3;
albumList.SetValue(Canvas.LeftProperty, left);
double top = root.Height - albums.Count() * 15 - 56;
albumList.SetValue(Canvas.TopProperty, top);
albumList.MouseLeftButtonUp += new MouseButtonEventHandler(albumList_MouseLeftButtonUp);
lst.SelectionChanged += new SelectionChangedEventHandler(lst_SelectionChanged);
}
}
}
void ShowPicture()
{
if (arrPics.Length == 0) return;

if (CurrentImg < 0)
{
CurrentImg = 0;
return;
}
if (CurrentImg > arrPics.Length - 1)
{
CurrentImg = arrPics.Length - 1;
return;
}

ImageSourceConverter objImgSrc = new ImageSourceConverter();
((Image)GetTemplateChild("mainImg")).SetValue(Image.SourceProperty,
objImgSrc.ConvertFromString(strFolder + "/" + arrPics[CurrentImg]));
}

Build the project to get the .dll file.


Using the control in Silverlight applications


Create a new Silverlight project and add a reference to the
control dll. The control can be added to the page like the
following.


<UserControl xmlns:my="clr-namespace:SLNuke;assembly=SLNuke"
x:Class="SLNukeTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<my:XAMLAlbum ImgSource="Babies" Width="600" Height="500" x:Name="XAlbum"
SlideDuration="3" DisableAlbumSelection="True"
BorderBrush="Black" BorderThickness="1" AlbumSrc="Album.xml" ></my:XAMLAlbum>
</Grid>
</UserControl>


Create a file Album.xml with the above format and copy to
ClientBin of the project. And copy the pictures to the folders
with same name as the album names written in the xml and place
under ClientBin (Note that I copied the pictures of the albums
Babies and Flowers only Nature will not show as the pictures are
not available in the attached project file SLNukeTest).





Points of Interest



The control has the advantage to zoom and play a slideshow.
Zooming functionality is useful when the picture clarity is not
compromised when the image width and height are decreased on the
screen. The album can be set to only one folder and the property
DisableAlbumSelection can be set to true to make the control to
show only one folder pictures and the folder selection button
will be hidden.


Visit http://www.codeproject.com/KB/silverlight/Silverlight_Pic_Album.aspx to download source code.