MigraDoc - only Last Page Footer - pdfsharp

I have this code:
Document document = new Document();
Section sec = document.AddSection();
Paragraph par;
for (int i = 0; i < 50; i++)
{
par = sec.AddParagraph();
par.AddText("Wiki je označení webů (nebo obecněji hypertextových dokumentů), které umožňují uživatelům přidávat obsah podobně jako v internetových diskusích, ale navíc jim také umožňují měnit stávající obsah; v přeneseném smyslu se jako wiki označuje software, který takovéto weby vytváří.Původně se termín wiki používal zcela opačně. Wiki bylo označení typu softwaru a weby postavené.");
}
par = sec.Headers.Primary.AddParagraph();
par.AddText("hlavicka");
Borders hranice = new Borders();
hranice.Width = 1;
sec.Headers.Primary.Format.Borders = hranice;
sec.AddImage("images.jpg");
par = sec.AddParagraph();
par.AddText("paticka");
PdfDocumentRenderer print = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
print.Document = document;
print.RenderDocument();
print.PdfDocument.Save("ahoj.pdf");
I need to make a Footer only on the last page. Is it possible?

MemoryStream PdfDocumnet()
{
Document pdfdoc = new MigraDoc.DocumentObjectModel.Document();
pdfdoc.Info.Title = "Doc Title";
pdfdoc.Info.Subject = "Doc Subject";
DefineProformaStyles(pdfdoc);
CreatePdf(pdfdoc);
MemoryStream stream = new MemoryStream();
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = pdfdoc;
renderer.RenderDocument();
renderer.Save(stream, false);
return stream;
}
private void CreatePdf(Document pdfDoc)
{
pdfDoc.DefaultPageSetup.HeaderDistance = "0.8cm";
pdfDoc.DefaultPageSetup.FooterDistance = "0.6cm";
MigraDoc.DocumentObjectModel.Section section = pdfDoc.AddSection();
section.PageSetup.TopMargin = "6.8cm"; //Unit.FromCentimeter(3.0);
section.PageSetup.BottomMargin = "3.4cm"; //Unit.FromCentimeter(3.0);
// HEADER ///////////////////////////////////////////////////////////////////////////////////
MigraDoc.DocumentObjectModel.Tables.Table tableh1 = section.Headers.Primary.AddTable();
Column colh1 = tableh1.AddColumn("10.8cm");
Column colh2 = tableh1.AddColumn("8cm");
colh2.Format.Alignment = ParagraphAlignment.Right;
// ...
// ... add content to header
// ...
//FOOTER for every page //////////////////////////////////////////////////////////////////////
MigraDoc.DocumentObjectModel.Tables.Table tablef2 = section.Footers.Primary.AddTable();
tablef2.Style = "Table";
//add content to footer
// BODY ///////////////////////////////////////////////////////////////////////////////////
MigraDoc.DocumentObjectModel.Tables.Table tableC = section.AddTable();
TextFrame frm0 = section.AddTextFrame();
Paragraph prg1 = section.AddParagraph();
//....
//.....
//FOOTER FOR ONLY LAST PAGE //////////////////////////////////////////////////////////////////
//Add an empty paragraph. If there is not enough space to fit in current page then ... page break
Paragraph emptyPar = section.AddParagraph();
emptyPar.Format.SpaceBefore = "2.6cm";
//add the special footer
string lastPageFooterImgFile = HttpContext.Current.Server.MapPath("/company/CompanyFooter.png");
TextFrame lastframe = section.AddTextFrame();
lastframe.Height = "2.6cm";
lastframe.RelativeVertical = RelativeVertical.Page;
lastframe.Top = "24cm"; // 24cm + 2.6cm + footer_for_every_page.Height = Page.Height
lastframe.AddImage(lastPageFooterImgFile);
}
private void DefineProformaStyles(Document Doc)
{
Doc.DefaultPageSetup.LeftMargin = "1.3cm";
MigraDoc.DocumentObjectModel.Style style = Doc.Styles["Normal"];
style = Doc.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("1cm", TabAlignment.Right);
style = Doc.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("1cm", TabAlignment.Center);
style = Doc.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Times New Roman";
style.Font.Size = 9;
style = Doc.Styles.AddStyle("Reference", "Normal");
style.ParagraphFormat.SpaceBefore = "1mm";
style.ParagraphFormat.SpaceAfter = "1mm";
style.ParagraphFormat.TabStops.AddTabStop("1cm", TabAlignment.Right);
}

There is no way to create a real footer on the last page.
You can create a TextFrame with your last paragraph. TextFrames are Shapes and can be placed at an absolute position on the page, so you can also place them where the Footer would be.

For example:
You need a 30mm place over the footer on the last page. (That could be a signature field.)
Define the PageSetup without this place (only footer hight + your distance from the bottom of the page)
Define your 30mm paragraph or table as TextFrame on a fix position: TextFrame.RelativeVertical = RelativeVertical.Page; frame.Top = ShapePosition.Bottom;
Define an empty paragraph as the last paragraph of the document with paragraph.Format.SpaceBefore = 30mm
Now the 30mm empty paragraph is on the end of all Documents and the signature overlapped it or the place for signature is not enough. Then the 30mm empty place forces a page break.

Related

How can itext7 remove the space between paragraph text and paragraph top?

Using itext7, I created a pdf with two paragraphs.
string cardPdf = "card.pdf"; float cardWidth = 266.5f; float cardHeight = 164.4f;
using (PdfDocument cardDoc = new PdfDocument(new PdfWriter(cardPdf)))
using (Document doc = new Document(cardDoc))
{
PdfPage page = cardDoc.AddNewPage(new iText.Kernel.Geom.PageSize(cardWidth, cardHeight));
Paragraph pg1 = new Paragraph("WriteParagraph 1").SetFontSize(10f);
pg1.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
doc.Add(pg1);
Paragraph pg2 = new Paragraph("WriteParagraph 2").SetFontSize(20f);
pg2.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
doc.Add(pg2);
}
I found that there are gaps at the top of the paragraph text and the background rectangle, and different font sizes cause different gaps. How can I remove the spacing.
You can use either of those methods to reduce space around to document.
Document Level
SetMargins(float topMargin, float rightMargin, float bottomMargin, float leftMargin);
SetTopMargin(float topMargin);
SetRightMargin(float rightMargin);
SetBottomMargin(float bottomMargin);
SetLeftMargin(float leftMargin);
Paragraph Level
SetMargins(float topMargin, float rightMargin, float bottomMargin, float leftMargin);
SetMarginTop(float topMargin);
SetMarginRight(float rightMargin);
SetMarginBottom(float bottomMargin);
SetMarginLeft(float leftMargin);
To control line spacing/leading for the paragraph.
SetMultipliedLeading(float leadingValue);
If need to control leading on overall document level.
SetProperty(int property, object value);
SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, float leading Value);
Try this:
string cardPdf = "card.pdf"; float cardWidth = 266.5f; float cardHeight = 164.4f;
using (PdfDocument cardDoc = new PdfDocument(new PdfWriter(cardPdf)))
using (Document doc = new Document(cardDoc))
{
doc.SetMargins(15f, 20f, 15f, 20f);
PdfPage page = cardDoc.AddNewPage(new iText.Kernel.Geom.PageSize(cardWidth, cardHeight));
Paragraph pg1 = new Paragraph("WriteParagraph 1").SetFontSize(10f);
pg1.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
pg1.SetMultipliedLeading(0.8f);
doc.Add(pg1);
Paragraph pg2 = new Paragraph("WriteParagraph 2").SetFontSize(20f);
pg2.SetMultipliedLeading(0.8f);
pg2.SetMarginTop(0f);
pg2.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
doc.Add(pg2);
}

How do you break a line of text within InDesign scripts?

So I'm new to InDesign CC scripting, but I really just need a very simple solution, or at least I hope that it's a simple solution. I have a script for adding a watermark to a document for export, however i'd like it to be on two lines and take up more space on the page rather than just one line. Below is the script I'm using:
var myDoc = app.activeDocument,
myPdfExportPreset = "[High Quality Print]",
myPdfFile = File(myDoc.fullName.fsName.replace(/.indd$/i, "") + ".pdf");
app.scriptPreferences.measurementUnit = MeasurementUnits.INCHES
var docHeight = myDoc.documentPreferences.pageHeight
var docWidth = myDoc.documentPreferences.pageWidth
with(myDoc.watermarkPreferences)
{
watermarkVisibility = true;
watermarkDoPrint = true;
watermarkDrawInBack = false;
watermarkText = "I would like the code to split between the word split and between";
watermarkFontFamily = "Helvetica";
watermarkFontStyle = "Bold";
watermarkFontPointSize = Math.round(docWidth * 7);
watermarkFontColor = [0, 0, 0];
watermarkOpacity = 15;
watermarkRotation = -25;
watermarkHorizontalPosition = WatermarkHorizontalPositionEnum.watermarkHCenter;
watermarkHorizontalOffset = 0;
watermarkVerticalPosition = WatermarkVerticalPositionEnum.watermarkVCenter;
watermarkVerticalOffset = 0;
}
If anyone has an idea on how to insert a line break, I'm not sure if it's like html where you can just <br> and be done with it, but that's kind of what I'm looking for, if that makes sense. Thanks so much in advance!

Unable to use multiple fonts with OpenXMl Cell styling

I have two different fonts defined in the style sheet but If I use the second style with StyleIndex=1 . I am unable to open the generated spread sheet. Any help would be greatly appreciated
My code
Private Function GenerateStyleSheet() As Stylesheet
Dim ss As Stylesheet = New Stylesheet()
Dim fonts1 As Fonts = New Fonts()
Dim f1 As Font = New Font()
Dim f1Size As FontSize = New FontSize()
f1Size.Val = 11D
f1.Append(f1Size)
Dim f2 As Font = New Font()
Dim b2 As Bold = New Bold()
Dim f2Size As FontSize = New FontSize()
f2Size.Val = 11D
f2.Append(b2)
f2.Append(f2Size)
fonts1.Append(f1)
fonts1.Append(f2)
fonts1.Count = fonts1.ChildElements.Count
ss.Append(fonts1)
Return ss
End Function
Function getBoldTextCell(ByVal cell As String, ByRef row As Row, ByVal val As String) As Row
Dim refCell As Cell = Nothing
Dim newCell As New Cell()
newCell.StyleIndex = 1 // 0 works
newCell.CellReference = cell
row.InsertBefore(newCell, refCell)
newCell.CellValue = New CellValue(val)
newCell.DataType = New EnumValue(Of CellValues)(CellValues.String)
Return (row)
End Function
XML Code:
<x:row xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:c r="A1" s="0" t="str">
<x:v>Request #</x:v>
</x:c>
<x:c r="B1" t="str">
<x:v>1</x:v>
</x:c>
</x:row>
Style Code:
<x:fonts count="2" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:font>
<x:sz val="11" />
</x:font>
<x:font>
<x:b />
<x:sz val="11" />
</x:font>
</x:fonts>
You cannot define styles like that . You need to create a Style with Fonts , Fills , Borders and create cellformats from defined Fonts , Fills , Borders as given below.
// <Fonts>
Font font0 = new Font(); // Default font
Font font1 = new Font(); // Bold font
Bold bold = new Bold();
font1.Append(bold);
Fonts fonts = new Fonts(); // <APENDING Fonts>
fonts.Append(font0);
fonts.Append(font1);
// <Fills>
Fill fill0 = new Fill(); // Default fill
Fills fills = new Fills(); // <APENDING Fills>
fills.Append(fill0);
// <Borders>
Border border0 = new Border(); // Defualt border
Borders borders = new Borders(); // <APENDING Borders>
borders.Append(border0);
// <CellFormats>
CellFormat cellformat0 = new CellFormat() { FormatId = 0, FillId = 0, BorderId = 0 };
CellFormat cellformat1 = new CellFormat(new Alignment() { Horizontal HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }) { FontId = 1 };
// <APENDING CellFormats>
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat0);
cellformats.Append(cellformat1);
// Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
workbookstylesheet.Append(fonts);
workbookstylesheet.Append(fills);
workbookstylesheet.Append(borders);
workbookstylesheet.Append(cellformats);
And later when defining cells , add style refference as
cell.StyleIndex=0 ; // Default style
cell1.StyleIndex=1 ; // Our defined style 1

Can PDFsharp automatically split a string over multiple pages?

I want to add the ability to generate a PDF of the content in my application (for simplicity, it will be text-only).
Is there any way to automatically work out how much content will fit in a single page, or to get any content that spills over one page to create a second (third, fourth, etc) page?
I can easily work it out for blocks of text - just split the text by a number of characters into a string array and then print each page in turn - but when the text has a lot of white space and character returns, this doesn't work.
Any advice?
Current code:
public void Generate(string title, string content, string filename)
{
PdfDocument document = new PdfDocument();
PdfPage page;
document.Info.Title = title;
XFont font = new XFont("Verdana", 10, XFontStyle.Regular);
List<String> splitText = new List<string>();
string textCopy = content;
int ptr = 0;
int maxCharacters = 3000;
while (textCopy.Length > 0)
{
//find a space in the text near the max character limit
int textLength = 0;
if (textCopy.Length > maxCharacters)
{
textLength = maxCharacters;
int spacePtr = textCopy.IndexOf(' ', textLength);
string startString = textCopy.Substring(ptr, spacePtr);
splitText.Add(startString);
int length = textCopy.Length - startString.Length;
textCopy = textCopy.Substring(spacePtr, length);
}
else
{
splitText.Add(textCopy);
textCopy = String.Empty;
}
}
foreach (string str in splitText)
{
page = document.AddPage();
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XTextFormatter tf = new XTextFormatter(gfx);
XRect rect = new XRect(40, 100, 500, 600);
gfx.DrawRectangle(XBrushes.Transparent, rect);
tf.DrawString(str, font, XBrushes.Black, rect, XStringFormats.TopLeft);
}
document.Save(filename);
}
You can download PDFsharp together with MigraDoc. MigraDoc will automatically add pages as needed, you just create a document and add your text as paragraphs.
See MigraDoc samples page:
http://pdfsharp.net/wiki/MigraDocSamples.ashx
MigraDoc is the recommended way.
If you want to stick to PDFsharp, you can use the XTextFormatter class (source included with PDFsharp) to create a new class that also supports page breaks (e.g. by returning the count of chars that fit on the current page and have the calling code create a new page and call the formatter again with the remaining text).

How to add an image to a table cell in iTextSharp using webmatrix

I have made a table with cells and interested in having an image in one of the cell.
Below is my code:
doc.Open();
PdfPTable table = new PdfPTable(2);
table.TotalWidth = 570f;
table.LockedWidth = true;
table.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
PdfPCell points = new PdfPCell(new Phrase("and is therefore entitled to 2 points", arialCertify));
points.Colspan = 2;
points.Border = 0;
points.PaddingTop = 40f;
points.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
table.AddCell(points);
// add a image
doc.Add(table);
Image jpg = Image.GetInstance(imagepath + "/logo.jpg");
doc.Add(jpg);
With the above code, the image shows in my pdf but I want it to be inside a cell so that I can add more cells to the right of the image.
On the very basic level you can simply add the image to a PdfPCell and add this cell to your table.
So using your code...
PdfPCell points = new PdfPCell(new Phrase("and is therefore entitled to 2 points", arialCertify));
points.Colspan = 2;
points.Border = 0;
points.PaddingTop = 40f;
points.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
// add a image
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imagepath + "/logo.jpg");
PdfPCell imageCell = new PdfPCell(jpg);
imageCell.Colspan = 2; // either 1 if you need to insert one cell
imageCell.Border = 0;
imageCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.AddCell(points);
// add a image
table.AddCell(imageCell);
doc.Add(table);
Update
Check your imagepath. This should be an absolute path to the image, and not relative like in a website page. Also, change your `/logo.jpg' to '\logo.jpg'
this is assuming imagepath is actually to the directory, and not the actual image...
I.E
Server.MapPath(imagepath) + "\\logo.jpg"

Resources