Reputation: 1189
I use MigraDoc to generate PDF file in c# from some database tables.
My major issue is for some of the paragraphs I add, they can’t be fitted into the current page, so are split to the next page, how can it be prevented? I want them to be in one page (current page or next page).
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AddLineBreak();
paragraph.AddLineBreak();
paragraph.AddLineBreak();
paragraph.Format.TabStops.ClearAll();
paragraph.Format.TabStops.AddTabStop("16cm", TabAlignment.Right, TabLeader.Lines);
paragraph.AddTab();
for (int i = 0; i < 20; i++)
{
Paragraph paragraphBody = paragraph.Section.AddParagraph();
FormattedText ft = paragraphBody.AddFormattedText("This is a title", TextFormat.Bold);
ft.Italic = true; ft.Font.Size = 11;
ft.Font.Color = Color.FromRgbColor((byte)255, Color.Parse("0x1E9BC6")); //equal to rgb(30, 155, 196);
ft.AddLineBreak();
//--detail:---adding text---------------------------------
String DetailText = "This is detail. This is detail. This is detail.This is detail.This is detail.This is detail.This is detail.This is detail. This is detail. This is detail. This is detail. This is detail. This is detail. This is detail. This is detail. This is detail. ";
FormattedText ftdet;
ftdet = paragraphBody.AddFormattedText(DetailText, TextFormat.NotBold);
ftdet.Font.Size = 10;
ftdet.Font.Name = "Arial";
ftdet.AddLineBreak();
ftdet.AddLineBreak();
ftdet.AddText("Event Date: " + DateTime.Now.ToString("MM/dd/yyyy h:mm tt"));
}
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
pdfRenderer.Document = doc;
pdfRenderer.RenderDocument();
//Save the PDF to a file:
string filename = "e:\\Report" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
pdfRenderer.PdfDocument.Save(filename);
Process.Start(filename);
Upvotes: 2
Views: 2138
Reputation: 21689
Paragraphs have a KeepTogether
property in the Format
member. If true, all lines of the paragraph are kept on one page.
There also is a KeepWithNext
property. If true, the last line of the paragraph will be on the same page as the first line of the next paragraph.
If you have a paragraph, simply write code like this:
paragraphBody.Format.KeepTogether = true;
See also:
http://www.nudoq.org/#!/Packages/PDFsharp-MigraDoc-GDI/MigraDoc.DocumentObjectModel/ParagraphFormat
Table cells will never break across pages. Therefore the properties KeepTogether
and KeepWithNext
have no effect when applied to paragraphs in table cells.
Upvotes: 2