Rectangle 27 2

Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on) http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx

Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)

CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
        book.ExcelWorkbook.ProtectWindows = false;

        book.ExcelWorkbook.ProtectStructure = false;

        var styles = book.Styles;
        WorksheetStyle defaultStyle = styles.Add("Default");
        var defStyles = defaultStyle;
        defStyles.Name = "Normal";
        defStyles.Font.FontName = "Calibri";
        defStyles.Font.Size = 11;
        defStyles.Font.Color = "#000000";
        defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;

        Worksheet sheet = book.Worksheets.Add("Sheet1");
        sheet.Table.DefaultRowHeight = 15f;
        sheet.Table.FullColumns = 1;
        sheet.Table.FullRows = 1;
        DataTable dt = new DataTable();  //=  your datatable

        //Header
        WorksheetRow HeaderRow = sheet.Table.Rows.Add();
        foreach (DataColumn col in dt.Columns)
        {
            HeaderRow.Cells.Add(col.ColumnName.ToString());

        }
        //Body
        foreach (DataRow dr in dt.Rows)
        {
            WorksheetRow row = sheet.Table.Rows.Add();
            foreach (DataColumn cols in dt.Columns)
            {
                  row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
            }
        }

        sheet.Options.Selected = true;
        sheet.Options.ProtectObjects = false;
        sheet.Options.ProtectScenarios = false;

        book.Save("path to file");

but convertion is not working in ur code error like this -- line 1 col 1: EOF expected

I think i am being a little too nice here, but i edited the post. Sometimes you have to mingle the code a little when converting.

how to Design the exported excel in asp.net? - Stack Overflow

asp.net
Rectangle 27 64

structure and meaning

However, there are assorted tags that were added in the past by stupid browser developers, which violate this basic principle.

However, the damage has already been done - too many people have learnt HTML as "put tags around stuff and stuff happens", rather than understanding the (important and useful) distinction between semantics and presentation, and those people have gone on to write books and tutorial, teaching other people the wrong way to write HTML, who themselves have done the same, and we've ended up with a right old mess.

Ideally, the center tag should never have existed, because people should have pointed out it's not 'real' HTML, and told the browser makers to go back and do it properly.

And for doing it properly... alignment is of course a presentation issue - applying layout and formatting to (structured) content - and the language to use for that is CSS.

However, yet again, stupid browser developers screwed up early CSS - and in many cases people creating web pages had to use incorrect HTML because the CSS simply didn't work.

These days, we're starting to get some useful functionality added to CSS, but there's still a lot that isn't implemented, and quite a few things that could have been implemented in far superior ways, but are now standardised so we're stuck with the old ways.

If stylesheets had been implemented by sensible people, you'd have all the controls you have in any decent office software - for aligning blocks and text, it'd work horizontally, vertically, upside-down, rotated, and so on - and it wouldn't be done in the stupid way of setting left/right margins to auto.

I'll add quickly, for completeness, the third 'level' for web pages, which deals with adding interactivity to an otherwise static page, which is of course the (mis-named) JavaScript.

Yet again, those stupid browser developers didn't know what they were doing. They picked an utterly inaccurate/invalid name (for marketing reasons), and again riddled a potentially great and powerful language with flaws, lack of functionality, and created something that was (until recently) hated by many people.

We have of course in the past few years seen a large uprising of JavaScript libraries which have helped to show some of the cool stuff JS has been capable of for years, hidden away many of the browser flaws which still exist in the browsers, and have partially helped to patch up CSS support so it's a bit more useful (still lots of things missing though).

+1 because is funny and mostly true. If you were following the debate on HTML 5 you would probably have been less optimistic on the fact we are starting to come to senses... Does the Microsoft attitude towards "extensibility of HTML" tells you something? ;)

AHHH!!! Depecrated, not "depreciated." And don't say it like that either. Makes me crazy. HTML tags don't suffer from inflation.

Actually @Erik, you spelled the key word incorrectly too. The word is deprecated, not depecrated. HTML tags (in addition to being inflation-proof) also do not come in crates - just guessing at what depecrated might mean if it were a word ;-)

Typo as a result of spazzing. I'll let my idiocy stand for the record. :P

Why is the
tag deprecated in HTML? - Stack Overflow

html tags center deprecated
Rectangle 27 64

structure and meaning

However, there are assorted tags that were added in the past by stupid browser developers, which violate this basic principle.

However, the damage has already been done - too many people have learnt HTML as "put tags around stuff and stuff happens", rather than understanding the (important and useful) distinction between semantics and presentation, and those people have gone on to write books and tutorial, teaching other people the wrong way to write HTML, who themselves have done the same, and we've ended up with a right old mess.

Ideally, the center tag should never have existed, because people should have pointed out it's not 'real' HTML, and told the browser makers to go back and do it properly.

And for doing it properly... alignment is of course a presentation issue - applying layout and formatting to (structured) content - and the language to use for that is CSS.

However, yet again, stupid browser developers screwed up early CSS - and in many cases people creating web pages had to use incorrect HTML because the CSS simply didn't work.

These days, we're starting to get some useful functionality added to CSS, but there's still a lot that isn't implemented, and quite a few things that could have been implemented in far superior ways, but are now standardised so we're stuck with the old ways.

If stylesheets had been implemented by sensible people, you'd have all the controls you have in any decent office software - for aligning blocks and text, it'd work horizontally, vertically, upside-down, rotated, and so on - and it wouldn't be done in the stupid way of setting left/right margins to auto.

I'll add quickly, for completeness, the third 'level' for web pages, which deals with adding interactivity to an otherwise static page, which is of course the (mis-named) JavaScript.

Yet again, those stupid browser developers didn't know what they were doing. They picked an utterly inaccurate/invalid name (for marketing reasons), and again riddled a potentially great and powerful language with flaws, lack of functionality, and created something that was (until recently) hated by many people.

We have of course in the past few years seen a large uprising of JavaScript libraries which have helped to show some of the cool stuff JS has been capable of for years, hidden away many of the browser flaws which still exist in the browsers, and have partially helped to patch up CSS support so it's a bit more useful (still lots of things missing though).

+1 because is funny and mostly true. If you were following the debate on HTML 5 you would probably have been less optimistic on the fact we are starting to come to senses... Does the Microsoft attitude towards "extensibility of HTML" tells you something? ;)

AHHH!!! Depecrated, not "depreciated." And don't say it like that either. Makes me crazy. HTML tags don't suffer from inflation.

Actually @Erik, you spelled the key word incorrectly too. The word is deprecated, not depecrated. HTML tags (in addition to being inflation-proof) also do not come in crates - just guessing at what depecrated might mean if it were a word ;-)

Typo as a result of spazzing. I'll let my idiocy stand for the record. :P

Why is the
tag deprecated in HTML? - Stack Overflow

html tags center deprecated
Rectangle 27 5

inside table layout use shrinkColumns property for columns you want them to be allowed to shrink for fitting

to shrink all columns or you can write instead of " *" ,the column indices you want to shrink , which in your case will be

<TableLayout
android:shrinkColumns="0,1"/>

note that column indices start from zero , so the latest code allows first (index=0) and second (index =1) columns to shrink.

tablelayout - Android table layout formatting problems - Stack Overflo...

android tablelayout
Rectangle 27 32

stretchColumns
android:shrinkColumns
TableLayout
<TableLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:stretchColumns="1"
  android:shrinkColumns="1">

The 1 values are the columns you want the changes to occur. You can specify more that one value like this:

android:stretchColumns="0,1"

or if you want the changes to happen to all you columns like this:

android:stretchColumns="*"

tablelayout - Android table layout formatting problems - Stack Overflo...

android tablelayout
Rectangle 27 2

I am not quite familiar with appengine but you need something Access Log Valve in Tomcat. Its attribute pattern ; a formatting layout identifying the various information fields from the request and response to be logged, or the word common or combined to select a standard format.

java - How to read and copy the HTTP servlet response output stream co...

java servlets logging servlet-filters
Rectangle 27 8

i had the same problem with my app and found the following solution:

<TableLayout 
   android:shrinkColumns="0"
   android:stretchColumns="1" 
   android:layout_width="match_parent"
   android:layout_height="wrap_content">
</TableLayout>

This works fine with 2 Columns.

tablelayout - Android table layout formatting problems - Stack Overflo...

android tablelayout
Rectangle 27 1

I'm not sure if I follow you exactly with the 3-4 files but here is what we tend to do. Also, let me first say that 99.9% of the time we use a repeater because of flexibility you have with layout and formatting of the data. Yes there are other controls that make basic data-binding easier with some more built in features but most times you don't need all the overhead.

We typically create a class to bind to the repeater. So if you need to combine multiple sources of data you can instantiate the class with the different predefined inputs. At this point all you need to do is create properties for each of the fields you want to bind to the repeater. And with the properties you can format the data however you like. For example combine first and last name into a fullname property. So if you need to refactor code because someone wants you to change the name format all you have to do is change the format class and your repeater never has to change.

<asp:Repeater ID="rptCalls" runat="server">

<ItemTemplate>      

            <tr runat="server" class='<%# Eval("RowClass") %>'>
                <td style="width: 40px;"><asp:Button ID="btnUpdate" runat="server" Text="View" CommandArgument='<%# Eval("Id") %>' CssClass="button" OnCommand="btnUpdate_Command" /></td>                  
                <td runat="server"><%# Eval("CallCount")%></td>
                <td style="width: 40px; white-space: nowrap; text-align: center;"><asp:Literal runat="server" Text='<%# Eval("TimeCalled") %>'></asp:Literal></td>                  
                <td><asp:Literal runat="server" Text='<%# Eval("Notified") %>'></asp:Literal></td>
                <td><asp:Literal runat="server" Text='<%# Eval("PatientName") %>'></asp:Literal></td>
                <td><asp:Literal runat="server" Text='<%# Eval("RequestorData") %>'></asp:Literal></td>
            </tr>
            </ItemTemplate>
        </asp:Repeater>

Here is an example of some of the fields in the class.

public string RowClass
    {
        get
        {
            return overduePolicy.IsOverdue() ? "overdue" : "";
        }
    }

    public string SearchCssClass
    {
        get
        {
            return notification.CallRequest.IsVoided ? "voided" : "";
        }
    }

The rowclass property is an example of something you can do with the properties. If you notice the opening TR tag it's Eval statement is Eval("RowClass") but it's assigned to the css "class" tag on TR. The RowClass property in the actual class checks a value and sets a specific text based on true false. This then highlights the row with a css style depending on true/false value.

Just an example of the freedom you have with repeaters.

Sorry for the long reply but I know when I'm stuck I like the same kind of feedback.

Well, your answer is exactly what I have now: separate classes for each Repeater, preformatting of all required fields in Page_Load and binding to Repeater. I like this architecture. You uses Eval("Field") as I see. But it is possible to use ((TYPE)Container.DataItem).Field there as well. This is the question.

You can but there are tradeoffs for each. As you mentioned above, Eval does late binding and uses reflection but you also only have to touch your viewmodel for changes. With dataitem, you have to cast which has better performance, but you have more maintenance. I think this is a business decision you need to make to decide is the performance hit ok for less modifications or not. That testing and performance is only something you decide based on all the factors within your organization. Everything else at this point would just be opinion/comparison based on what it seems you already know.

c# - DataBinding: Eval() vs Container.DataItem casting -- best practic...

c# asp.net data-binding eval
Rectangle 27 5

I had the same problem and solved it by adding

android:stretchColumns="0"
android:layout_width="0dp"

on the TextView that was too long.

and what exactly this means ? how did you figure out that this is the solution?

tablelayout - Android table layout formatting problems - Stack Overflo...

android tablelayout
Rectangle 27 242

android:layout_height="fill_parent"

Edit - took me a while to find, but looking at the source helped me pinpoint adjustViewBounds. You might want to try adding android:adjustViewBounds="true" to your ImageViews. Surprisingly, this defaults to false.

Changing the layout_height to fill_parent made no difference but setting adjustViewBounds to true did the trick! I'm amazed I've done so much work with the various views and somehow managed to not notice that parameter! Thank you :)

Me too. I had assumed that it would default to true, but somehow never ran into this issue.

I really ask myself, why "false" is the default value for that important setting. @MatthewWillis you made my day ;) Thanks a lot.

layout - Android ImageView size not scaling with source image - Stack ...

android layout formatting imageview custom-view
Rectangle 27 56

Colin Pickard has an excellent answer, but there is one 'watch out' with this. There are instances (I haven't figured out the cause yet) where the total length of the "CMG=........GC=...." entry in the file is different from one excel file to the next. In some cases, this entry will be 137 bytes, and in others it will be 143 bytes. The 137 byte length is the odd one, and if this happens when you create your file with the '1234' password, just create another file, and it should jump to the 143 byte length.

If you try to paste the wrong number of bytes into the file, you will lose your VBA project when you try to open the file with Excel.

This is not valid for Excel 2007/2010 files. The standard .xlsx file format is actually a .zip file containing numerous sub-folders with the formatting, layout, content, etc, stored as xml data. For an unprotected Excel 2007 file, you can just change the .xlsx extension to .zip, then open the zip file and look through all the xml data. It's very straightforward.

However, when you password protect an Excel 2007 file, the entire .zip (.xlsx) file is actually encrypted using RSA encryption. It is no longer possible to change the extension to .zip and browse the file contents.

Then you need to use standard zip hacking tools. Its no longer a "how do i back an excel file" problem.

@Anonymous Type: I think a zip cracking tool won't help. As I understand Stewbob, it's not the file entries in the zip file that are encrypted, but the whole zip file itself, which should include the header and the central directory.

Is there a way to crack the password on an Excel VBA Project? - Stack ...

excel excel-vba passwords
Rectangle 27 56

Colin Pickard has an excellent answer, but there is one 'watch out' with this. There are instances (I haven't figured out the cause yet) where the total length of the "CMG=........GC=...." entry in the file is different from one excel file to the next. In some cases, this entry will be 137 bytes, and in others it will be 143 bytes. The 137 byte length is the odd one, and if this happens when you create your file with the '1234' password, just create another file, and it should jump to the 143 byte length.

If you try to paste the wrong number of bytes into the file, you will lose your VBA project when you try to open the file with Excel.

This is not valid for Excel 2007/2010 files. The standard .xlsx file format is actually a .zip file containing numerous sub-folders with the formatting, layout, content, etc, stored as xml data. For an unprotected Excel 2007 file, you can just change the .xlsx extension to .zip, then open the zip file and look through all the xml data. It's very straightforward.

However, when you password protect an Excel 2007 file, the entire .zip (.xlsx) file is actually encrypted using RSA encryption. It is no longer possible to change the extension to .zip and browse the file contents.

Then you need to use standard zip hacking tools. Its no longer a "how do i back an excel file" problem.

@Anonymous Type: I think a zip cracking tool won't help. As I understand Stewbob, it's not the file entries in the zip file that are encrypted, but the whole zip file itself, which should include the header and the central directory.

How about when the file you want to get into has the shorter keys? Just keep creating vba docs until you get one that has 137?

Are you sure that the entire zipfile is encrypted when you lock the VBA project? I can still open the zipfile and see the file structure.... And subfolder xl\ contains the file vbaProject.bin which has the familiar "CMG=... GC=" hashing block.

Is there a way to crack the password on an Excel VBA Project? - Stack ...

excel excel-vba passwords
Rectangle 27 115

To make the main content a new Block Formatting Context or not?

Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

With my bold, it's the establish bit that is important

What this means is that the element you use overflow (anything other than visible) or float or inline-block..etc on becomes responsible for the layout of its child elements. It's the child elements which are then "contained", whether that's floats or collapsing margins they should be wholly contained by their bounding parent.

In a block formatting context, each box's left outer edge touches the left edge of the containing block (for right-to-left formatting, right edges touch)

What the above line means:

Because a box can only be rectangular and not irregular shaped this means a new block formatting context between two floats (or even beside one) will not wrap around neighbouring side floats. The inner, child boxes can only extend as far as to touch their parents left (or right in RTL) edge. It's this behaviour that's useful for columnar style layouts. The main use of it however is to stop floats, say in a "main content" div, actually clearing floated side columns, i.e. floats that appear earlier in the source code.

In normal circumstances floats are supposed to clear all previous floated elements, that's previously floated in the whole source code, not just your displayed "column" The telling quote from the "float clearance specs" is:

This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box. The 'clear' property does not consider floats inside the element itself or in other block formatting contexts

So say you have a three column layout where the left and right columns are floated left and right respectively, the side columns are now in new Block Formatting Contexts, because they are floated (remember float is also one of the properties that establish a new BFC), so you can happily float list elements inside them and they only clear floats which are already inside the side columns they no longer care about floats previously in the source code

Now that middle column, you can simply margin it from both sides so that it appears to sit neatly between the two side floated columns and take the remaining width, a common way to get desired width if the centre column is "fluid" - which will be fine until you need to use floats/clearance inside your content div (a common occurrence for those using "clearfix" hacks or templates including them)

In general this is fine, especially if you have no background colours or internal (in the main content) floats - notice the floats are fine (not cleared yet) they're doing probably what you except them to but they, the H3's top margin and the p's bottom margin are not actually really contained by the content div (lightgrey background).

So to the same simple margined scenario of above code add:

.clear-r {clear: right;}

to the CSS, and change the second HTML floated box to:

<div class="floated clear-r"> this a floated cleared box</div>

This time you get this:

The second float is clearing the right side but it's clearing the whole height of the right column. The right column is floated earlier in the source code so it's clearing it as told! Probably not the desired effect though, also note the h3 and p margins are still collapsed (not contained).

and finally make the main content column take responsibility - become a Block Formatting Context - for its contents : remove margin: 0 200px; from the main content CSS and ADD overflow: hidden; and you get this:

#left-col {
  border: 1px solid #000;
  width: 180px;
  float: left;
}
#right-col {
  border: 1px solid #000;
  width: 180px;
  float: right;
  height: 200px;
}
#content {
  background: #eee;
  overflow: hidden;
}
.floated {
  float: right;
  width: 180px;
  height: 100px;
  background: #dad;
}
.clear-r {
  clear: right;
}
<div id="left-col">left column</div>
<div id="right-col">right column</div>

<div id="content">
  <h3>Main Content</h3>
  <p>Lorem ipsum etc..</p>
  <div class="floated">this a floated box</div>
  <div class="floated clear-r">this a floated cleared box</div>
</div>

This is probably much more like what you would expect to happen, note now the floats are contained, they clear properly ignoring the right side column, and also the h3 and p margins are contained instead of collapsed.

With the extensive use of resets these days the margins are less noticeable (and IE still doesn't get them quite right) however what just happened to the centre "main content" is that it became a Block Formatting Context and is now responsible for its own child (descendant) elements. It's actually very similar to Microsoft's early days notion of hasLayout, it uses the same properties display: inline-block, float, and overflow anything other than visible, and of course table cells always have layout.. it is however without the bugs ;)

When you say "but floating elements are ignored when user agent draws box and take them into account when they fill out content."

Yes floats normally overlay their container boxes, is that what you mean about parent boundaries? When a block element is drawn and it contains a float the block parent itself is drawn as a rectangle under the float and it is the "inline anonymous boxes" or simply "line boxes" of the other child elements that are shortened to make room for the float

#content {
  background: #eee;
  color #000;
  border: 3px solid #444;
}
.float {
  background: rgba(0, 0, 255, 0.5);
  border: 1px solid #00f;
  width: 150px;
  height: 150px;
  float: left;
  margin: 10px;
}
p {
  background: #444;
  color: #fff;
}
<div id="content">
  <div class="float">floated box</div>
  <h3>This is a content box</h3>
  <p>it contains a left floated box, you can see the actual content div does go under the float, but that it is the &lt;h3&gt; and &lt;p&gt; <b>line boxes</b> that are shortened to make room for the float, this is normal behaviour</p>
</div>

You see that the parent element doesn't actually contain the float, as in it doesn't wrap it entirely.. the float is simply floating on top of the content - if you were to keep adding content to the div it would eventually wrap underneath the float because there would be no need for the (anonymous) "line boxes" of the p element to shorten themselves any more.

I've coloured the paragraph element so you can see that it too actually goes under the float, the darkgray background is where the paragraph starts, the white text is where the "anonymous line box" starts - it's only actually them that "make room" for the float, unless you tell it otherwise (i.e. you change the context)

Again referring to the above picture, if you were to margin the left side of thep element, yes it will stop the text wrapping under the bottom of the float because the "line boxes" (the white text) will only touch the left edge of their container, and you will bring the coloured background of the p to the right, clear of the float, but you won't have changed the behaviour of the p's formatting context. Like the centre column in the first picture way above ;)

+1 You have put some work into this :).

@eileen there's two things going on - I think your extra question is explained by the first example.. the purple floated boxes appear after the content because that's where they are in the source, a float does not float to the top, go above previous content (as in it's top margin cannot be higher than where it should be) - the left and right columns are also floated boxes which are earlier in the source and without the middle column becoming a new BFC if you try and clear the purple floats they will also clear the earlier in source side floated columns.. does that help?

@eileen that link is describing block level elements and inline level element, just the basics not so much in a formatting context. block elements will always take 100% width and sit on top of each other (by default) - inline elements sit side by side, like links, spans etc.. the don't even take a width or height so they have no option. A floated element automatically becomes a block level element, so if you float an inline level <span> it becomes like a block level <div>.

cont.. the reason the p's background goes under the float is because floated elements are removed from the flow, as in the neighbouring elements really don't know they're there, and because they belong to the same formatting context the p looks to it's parent container for it's dimensions.. (that's why you can't put a 100% wide thing next to a float - because to it 100% is 100% of the container. Only the anonymous boxes finally figure out the float is there ;)

@clairesuzy - The image you posted is out, could you please repost?

How does the CSS Block Formatting Context work? - Stack Overflow

css
Rectangle 27 7

You can't do this in regular Tex: the DVI format specifies the coordinate bounds in the preamble (maxv, maxh) and has no opcodes to change the values once set. DVI doesn't really have a notion of page dimension anyway; cf. my answer to the dvi generation: no bounding box question. You might be able to mess about with Postscript specials and do this that way: I don't know how.

In Pdftex (and Xetex), you can change pdf dimensions; e.g.:

It's best to issue these dimension changes before anything has been typeset on the page, since these dimensions affect how Tex lays out content. Also note that your choice of margins, etc., should be guided by page dimensions.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

layout - Change paper size in the middle of a latex document? - Stack ...

layout latex formatting parameters
Rectangle 27 56

First, there is a bug with CoreGraphics PDF generation in iOS that results in corrupted PDFs. I know this issue exists up to and including iOS 4.1 (I haven't tested iOS 4.2). The issue is related to fonts and only shows up if you include text in your PDF. The symptom is that, when generating the PDF, you'll see errors in the debug console that look like this:

<Error>: can't get CIDs for glyphs for 'TimesNewRomanPSMT'

The tricky aspect is that the resulting PDF will render fine in some PDF readers, but fail to render in other places. So, if you have control over the software that will be used to open your PDF, you may be able to ignore this issue (e.g., if you only intend to display the PDF on the iPhone or Mac desktops, then you should be fine using CoreGraphics). However, if you need to create a PDF that works anywhere, then you should take a closer look at this issue. Here's some additional info:

As a workaround, I've used libHaru successfully on iPhone as a replacement for CoreGraphics PDF generation. It was a little tricky getting libHaru to build with my project initially, but once I got my project setup properly, it worked fine for my needs.

Second, depending on the format/layout of your PDF, you might consider using Interface Builder to create a view that serves as a "template" for your PDF output. You would then write code to load the view, fill in any data (e.g., set text for UILabels, etc.), then render the individual elements of the view into the PDF. In other words, use IB to specify coordinates, fonts, images, etc. and write code to render various elements (e.g., UILabel, UIImageView, etc.) in a generic way so you don't have to hard-code everything. I used this approach and it worked out great for my needs. Again, this may or may not make sense for your situation depending on the formatting/layout needs of your PDF.

My implementation is part of a commercial product meaning that I can't share the full code, but I can give a general outline:

I created a .xib file with a view and sized the view to 850 x 1100 (my PDF was targeting 8.5 x 11 inches, so this makes it easy to translate to/from design-time coordinates).

- (UIView *)loadTemplate
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ReportTemplate" owner:self options:nil];
    for (id view in nib) {
        if ([view isKindOfClass: [UIView class]]) {
            return view;
        }
    }

    return nil;
}

I then fill in various elements. I used tags to find the appropriate elements, but you could do this other ways. Example:

UILabel *label = (UILabel *)[templateView viewWithTag:TAG_FIRST_NAME];
if (label != nil) {
    label.text = (firstName != nil) ? firstName : @"None";

Then I call a function to render the view to the PDF file. This function recursively walks the view hierarchy and renders each subview. For my project, I need to support only Label, ImageView, and View (for nested views):

- (void)addObject:(UIView *)view
{
    if (view != nil && !view.hidden) {
        if ([view isKindOfClass:[UILabel class]]) {
            [self addLabel:(UILabel *)view];
        } else if ([view isKindOfClass:[UIImageView class]]) {
            [self addImageView:(UIImageView *)view];
        } else if ([view isKindOfClass:[UIView class]]) {
            [self addContainer:view];
        }
    }
}

As an example, here's my implementation of addImageView (HPDF_ functions are from libHaru):

- (void)addImageView:(UIImageView *)imageView
{
    NSData *pngData = UIImagePNGRepresentation(imageView.image);
    if (pngData != nil) {
        HPDF_Image image = HPDF_LoadPngImageFromMem(_pdf, [pngData bytes], [pngData length]);
        if (image != NULL) {
            CGRect destRect = [self rectToPDF:imageView.frame];

            float x = destRect.origin.x;
            float y = destRect.origin.y - destRect.size.height;
            float width = destRect.size.width;
            float height = destRect.size.height;

            HPDF_Page page = HPDF_GetCurrentPage(_pdf);
            HPDF_Page_DrawImage(page, image, x, y, width, height);
        }
    }
}

Hopefully that gives you the idea.

Do you have any examples of how to use an XIB as a template?

iphone - iOS SDK - Programmatically generate a PDF file - Stack Overfl...

iphone objective-c ipad ios pdf-generation
Rectangle 27 1

android:stretchColumns = " (number of actual col) - 1 "

tablelayout - Android table layout formatting problems - Stack Overflo...

android tablelayout
Rectangle 27 5

Here is an example which uses a KOMA-Script class to insert an A3 page in the middle of the document:

\documentclass[version=last, pagesize=auto, paper=a4]{scrartcl}

\begin{document}

\null
\clearpage

\KOMAoptions{paper=a3}
\recalctypearea

\null
\clearpage

\KOMAoptions{paper=a4}
\recalctypearea

\null

\end{document}

layout - Change paper size in the middle of a latex document? - Stack ...

layout latex formatting parameters
Rectangle 27 9

Strangely android:layout_height="fill_parent" and android:adjustViewBounds="true" didn't help. The problem I had is image was getting displayed, but with block row on top and black row on bottom of image. Setting scale type to "centerCrop" helped me. I guess, the reason being my image size was small.

layout - Android ImageView size not scaling with source image - Stack ...

android layout formatting imageview custom-view
Rectangle 27 50

The problem of converting an AST back into source code is generally called "prettyprinting". There are two subtle variations: regenerating the text matching the original as much as possible (I call this "fidelity printing"), and (nice) prettyprinting, which generates nicely formatted text. And how you print matters depending on whether coders will be working on the regenerated code (they often want fidelity printing) or your only intention is to compile it (at which point any legal prettyprinting is fine).

To do prettyprinting well requires usually more information than a classic parser collects, aggravated by the fact that most parser generators don't support this extra-information collection. I call parsers that collect enough information to do this well "re-engineering parsers". More details below.

The fundamental way prettyprinting is accomplished is by walking the AST ("Visitor pattern" as you put it), and generating text based on the AST node content. The basic trick is: call children nodes left-to-right (assuming that's the order of the original text) to generate the text they represent, interspersing additional text as appropriate for this AST node type. To prettyprint a block of statements you might have the following psuedocode:

PrettyPrintBlock:
     Print("{"}; PrintNewline();
     Call PrettyPrint(Node.children[1]); // prints out statements in block
     Print("}"); PrintNewline();
     return;


 PrettyPrintStatements:
     do i=1,number_of_children
         Call PrettyPrint(Node.children[i]); Print(";"); PrintNewline(); // print one statement
     endo
     return;

Note that this spits out text on the fly as you visit the tree.

There's a number of details you need to manage:

All of this "extra" information is collected by a good reenginering parser. Conventional parsers usually don't collect any of it, which makes printing acceptable ASTs difficult.

A more principled approach distinguishes prettyprinting whose purpose is nice formatting, from fidelity printing whose purpose is to regenerate the text to match the original source to a maximal extent. It should be clear that at the level of the terminals, you pretty much want fidelity printing. Depending on your purpose, you can pretty print with nice formatting, or fidelity printing. A strategy we use is to default to fidelity printing when the AST hasn't been changed, and prettyprinting where it has (because often the change machinery doesn't have any information about column numbers or number radixes, etc.). The transformations stamp the AST nodes that are newly generated as "no fidelity data present".

An organized approach to prettyprinting nicely is to understand that virtually all text-based programming language are rendered nicely in terms of rectangular blocks of text. (Knuth's TeX document generator has this idea, too). If you have some set of text boxes representing pieces of the regenerated code (e.g., primitive boxes generated directly for the terminal tokens), you can then imagine operators for composing those boxes: Horizontal composition (stack one box to the right of another), Vertical (stack boxes on top of each other; this in effect replaces printing newlines), Indent (Horizontal composition with a box of blanks), etc. Then you can construct your prettyprinter by building and composing text boxes:

PrettyPrintBlock:
     Box1=PrimitiveBox("{"); Box2=PrimitiveBox("}");
     ChildBox=PrettyPrint(Node.children[1]); // gets box for statements in block
     ResultBox=VerticalBox(Box1,Indent(3,ChildBox),Box2);
     return ResultBox;

PrettyPrintStatements:
     ResultBox=EmptyBox();
     do i=1,number_of_children
         ResultBox=VerticalBox(ResultBox,HorizontalBox(PrettyPrint(Node.children[i]); PrimitiveBox(";")
     endo
     return;

The real value in this is any node can compose the text boxes produced by its children in arbitrary order with arbitrary intervening text. You can rearrange huge blocks of text this way (imagine VBox'ing the methods of class in method-name order). No text is spit out as encountered; only when the root is reached, or some AST node where it is known that all the children boxes have been generated correctly.

Our DMS Software Reengineering Toolkit uses this approach to prettyprint all the languages it can parse (including PHP, Java, C#, etc.). Instead of attaching the box computations to AST nodes via visitors, we attach the box computations in a domain-specific text-box notation

directly to the grammar rules, allowing us to succinctly express the grammar (parser) and the prettyprinter ("anti-parser") in one place. The prettyprinter box rules are compiled automatically by DMS into a visitor. The prettyprinter machinery has to be smart enough to understand how comments play into this, and that's frankly a bit arcane but you only have to do it once. An DMS example:

block = '{' statements '}' ; -- grammar rule to recognize block of statements
<<PrettyPrinter>>: { V('{',I(statements),'}'); };

You can see a bigger example of how this is done for Wirth's Oberon programming language PrettyPrinter showing how grammar rules and prettyprinting rules are combined. The PHP Front End looks like this but its a lot bigger, obviously.

A more complex way to do prettyprinting is to build a syntax-directed translator (means, walk the tree and build text or other data structures in tree-visted order) to produce text-boxes in a special text-box AST. The text-box AST is then prettyprinted by another tree walk, but the actions for it are basically trivial: print the text boxes. See this technical paper: Pretty-printing for software reengineering

An additional point: you can of course go build all this machinery yourself. But the same reason that you choose to use a parser generator (its a lot of work to make one, and that work doesn't contribute to your goal in an interesting way) is the same reason you want to choose an off-the-shelf prettyprinter generator. There are lots of parser generators around. Not many prettyprinter generators. [DMS is one of the few that has both built in.]

Thanks for that pretty extensive description, I will try those tips in the next few days. PS: The Simlpe Language Example link gives me a 404.

@nikic: It was wrong on my first submission but I corrected it. Try again.

Okay, Thanks for your help Ira :) I managed to implement the pretty printer (it took quite some time to get rid of many many edge-case bugs). Though it doesn't retain any whitespace or comment information. I figured that it would be to difficult to implement. You can find the resulting package over at github: github.com/nikic/PHP-Parser :) Thanks again!

Losing people's comments is pretty much a sure fire way to get them to reject your prettyprinted code. Just sayin'.

Sorry if you don't like my definition. I use the term prettyprinting to include any AST to text conversion, whether that forces a standard layout, preserves the layout of the original, or mixes the two together in different parts of the tree for the same language or mixes the two because the tree is a hybrid tree containing subtrees of one language with arbitrary subtrees of another (and yes, I have machinery to do all of that seamlessly). I'm not pleased with "unparsing" ; while what it does is logically inverse of parsing, it doesn't actually do any parsing at all so the term confuses.

php - Compiling an AST back to source code - Stack Overflow

php compiler-construction abstract-syntax-tree
Rectangle 27 6

I had similar problem and my solution was to set android:scaleType="fitEnd" attribute of ImageView in XML layout file.

android:scaleType="fitXY"
fitXY

layout - Android ImageView size not scaling with source image - Stack ...

android layout formatting imageview custom-view