after insert header in aspose.word I want insert BreackNewPage
but
Exception occurred when insert section break in aspose.word for .Net
my Code Is in here:
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape shape = builder.InsertImage(dataDir);
shape.Height = builder.PageSetup.PageHeight - 200;
shape.Width = builder.PageSetup.PageWidth - 50;
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeHorizontalPositionRelativeHorizontalPosition.Page;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.InsertBreak(BreakType.SectionBreakNewPage);
Your cursor needs to be inside the "main Story" to be able to insert the requested break. Please see following code:
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
Shape shape = builder.InsertImage(MyDir + #"aspose.words.jpg");
shape.Height = builder.PageSetup.PageHeight - 200;
shape.Width = builder.PageSetup.PageWidth - 50;
shape.WrapType = WrapType.None;
shape.BehindText = true;
shape.RelativeVerticalPosition = RelativeVerticalPosition.Page;
shape.VerticalAlignment = VerticalAlignment.Center;
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.SectionBreakNewPage);
doc.Save(MyDir + #"17.11.docx");
I work with Aspose as Developer Evangelist.
You can use a simple function provided by aspose.word as
Document doc = new Document();
DocumentBuilder documentBuilder= new DocumentBuilder(doc);
documentBuilder.MoveToDocumentEnd(); //moving cursor to end of page.
documentBuilder.InsertBreak(BreakType.SectionBreakNewPage); // creating new page.
documentBuilder.PageSetup.ClearFormatting(); //clear formatting.
Related
I'm trying to align my paragraph in the center for ppt but its not working!
This is my code:
public static void ChangeSlidePart(SlidePart slidePart1,PresentationPart presentationPart)
{
Slide slide1 = slidePart1.Slide;
CommonSlideData commonSlideData1 = slide1.GetFirstChild<CommonSlideData>();
ShapeTree shapeTree1 = commonSlideData1.GetFirstChild<ShapeTree>();
Shape shape1 = shapeTree1.GetFirstChild<Shape>();
TextBody textBody1 = shape1.GetFirstChild<TextBody>();
D.Paragraph paragraph1 = textBody1.GetFirstChild<D.Paragraph>();
D.Run run1 = paragraph1.GetFirstChild<D.Run>();
run1.RunProperties= new D.RunProperties() {FontSize = 6600};
run1.RunProperties.Append(new D.LatinFont() { Typeface = "Arial Black" });
//run1.Append(runProperties1);
D.Text text1 = run1.GetFirstChild<D.Text>();
text1.Text = "Good day";
}
I tried adding to this paragraph properties with the corresponding justification but nothing was updated.
It doesn't seem that easy to do this using Open XML SDK. With Aspose.Slides for .NET, you can align a paragraph as shown below:
// The presentation variable here is an instance of the Presentation class.
var firstShape = (IAutoShape) presentation.Slides[0].Shapes[0];
var firstParagraph = firstShape.TextFrame.Paragraphs[0];
firstParagraph.ParagraphFormat.Alignment = TextAlignment.Center;
You can also evaluate Aspose.Slides Cloud SDK for .NET. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to align a paragraph using Aspose.Slides Cloud:
var slidesApi = new SlidesApi("my_client_id", "my_client_key");
var filePath = "example.pptx";
var slideIndex = 1;
var shapeIndex = 1;
var paragraphIndex = 1;
var paragraph = slidesApi.GetParagraph(
filePath, slideIndex, shapeIndex, paragraphIndex);
paragraph.Alignment = Paragraph.AlignmentEnum.Center;
slidesApi.UpdateParagraph(
filePath, slideIndex, shapeIndex, paragraphIndex, paragraph);
I work as a Support Developer at Aspose.
I added a sample project to reproduce the problem to the GitHub repo, I hope this helps:
Click to go to the Github repo
I need to add text and a number of page to a PDF, this PDF is from an invoice.
I already tried using events (but the examples are for java, and are incomplete, or I think they are), and it's not working, I'm getting the same error, and in that way text cannot be aligned.
As I said, I've trying to achieve this using a table and a canvas, the code works fine if the PDF has only one page.
But with more than one page I get this error:
This exception was originally thrown at this call stack: KernelExtensions.Get<TKey,
TValue>(System.Collections.Generic.IDictionary, TKey)
iText.Kernel.Pdf.PdfDictionary.Get(iText.Kernel.Pdf.PdfName, bool)
iText.Kernel.Pdf.PdfDictionary.GetAsNumber(iText.Kernel.Pdf.PdfName)
iText.Kernel.Pdf.PdfPage.GetRotation()
iText.Kernel.Pdf.Canvas.PdfCanvas.PdfCanvas(iText.Kernel.Pdf.PdfPage)
BoarGiveMeMoar.Invoices.InvoiceToPdf.AddFooter(iText.Layout.Document)
in InvoiceToPdf.cs
BoarGiveMeMoar.Invoices.InvoiceToPdf.FillPdf.AnonymousMethod__4() in InvoiceToPdf.cs
System.Threading.Tasks.Task.InnerInvoke() in Task.cs
System.Threading.Tasks.Task..cctor.AnonymousMethod__274_0(object) in Task.cs
System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread,
System.Threading.ExecutionContext, System.Threading.ContextCallback,
object) in ExecutionContext.cs
...
[Call Stack Truncated]
This is my code, but I get the error from above:
private readonly int smallFontSize = 6;
private readonly int stdFontSize = 7;
public void FillPdf(string filename)
{
using var pdfWriter = new PdfWriter(filename);
using var pdfDoc = new PdfDocument(pdfWriter);
using var doc = new Document(pdfDoc, PageSize.LETTER);
doc.SetMargins(12, 12, 36, 12);
AddData(doc);
AddFooter(doc);
doc.Close();
}
private void AddData(Document doc)
{
Table table = new Table(UnitValue.CreatePercentArray(5)).UseAllAvailableWidth();
PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
for (int i = 0; i < 250; i++)
{
var cell = new Cell(1, 5)
.Add(new Paragraph($"My Favorite animals are boars and hippos")
.SetFontSize(stdFontSize).SetFont(bold));
cell.SetBorder(Border.NO_BORDER);
cell.SetPadding(0);
table.AddCell(cell);
}
doc.Add(table);
}
private void AddFooter(Document doc)
{
if (doc is null)
return;
Table table = new Table(UnitValue.CreatePercentArray(60)).UseAllAvailableWidth();
int numberOfPages = doc.GetPdfDocument().GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
PdfPage page = doc.GetPdfDocument().GetPage(i);
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(
0,
0,
page.GetPageSize().GetWidth(),
15);
Canvas canvas = new Canvas(pdfCanvas, doc.GetPdfDocument(), rectangle);
var cell = new Cell(1, 20).SetFontSize(smallFontSize);
cell.SetBorder(Border.NO_BORDER);
cell.SetPadding(0);
table.AddCell(cell);
cell = new Cell(1, 20).Add(new Paragraph("This document is an invoice")
.SetTextAlignment(TextAlignment.CENTER)).SetFontSize(smallFontSize);
cell.SetBorder(Border.NO_BORDER);
cell.SetPadding(0);
table.AddCell(cell);
cell = new Cell(1, 10).SetFontSize(smallFontSize);
cell.SetBorder(Border.NO_BORDER);
cell.SetPadding(0);
table.AddCell(cell);
cell = new Cell(1, 7)
.Add(new Paragraph($"Page {string.Format(CultureInfo.InvariantCulture, "{0:#,0}", i)} of {string.Format(CultureInfo.InvariantCulture, "{0:#,0}", numberOfPages)} ")
.SetTextAlignment(TextAlignment.RIGHT)).SetFontSize(smallFontSize);
cell.SetBorder(Border.NO_BORDER);
cell.SetPadding(0);
table.AddCell(cell);
cell = new Cell(1, 3).SetFontSize(smallFontSize);
cell.SetBorder(Border.NO_BORDER);
cell.SetPadding(0);
table.AddCell(cell);
canvas.Add(table).SetFontSize(smallFontSize);
canvas.Close();
}
}
Example way to call the code:
new InvoiceToPdf()
.FillPdf(#$"{Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}\StackOverflow Invoice Test.pdf");
I get an error on this line that creates a new PdfCanvas
PdfCanvas pdfCanvas = new PdfCanvas(page);
So, anyone of you has a solution?
By default to decrease memory consumption a bit the pages of the PDF document you are creating are flushed as they fill up.
It means that when the content is written e.g. on page 3 of the document, the content of the page 1 is already written to the disk and it's too late to add more content there.
One option is to first create a document and close it, then open it with reader and writer, i.e.: new PdfDocument(PdfReader, PdfWriter), create Document around PdfDocument again and append content to the document as you do now:
public void FillPdf(string filename)
{
{
using var pdfWriter = new PdfWriter(tempFilename);
using var pdfDoc = new PdfDocument(pdfWriter);
using var doc = new Document(pdfDoc, PageSize.LETTER);
doc.SetMargins(12, 12, 36, 12);
AddData(doc);
doc.Close();
}
{
using var pdfWriter = new PdfWriter(filename);
using var pdfReader = new PdfReader(tempFilename);
using var pdfDoc = new PdfDocument(pdfReader, pdfWriter);
using var doc = new Document(pdfDoc, PageSize.LETTER);
doc.SetMargins(12, 12, 36, 12);
AddFooter(doc);
doc.Close();
}
}
Second option is not to flush the content as soon as possible and keep it in memory instead. You can do that by only making a slight modification in your code: pass third parameter to Document constructor
using var doc = new Document(pdfDoc, PageSize.LETTER, false);
Please keep in mind that second option might result in additional empty page being created at the end of your document in some corner cases (e.g. when you add such a large image to your document that it doesn't even fit into a full page), so use it carefully. It should not create any problems with you are dealing with regular simple content though
I am trying to print the contents of a rich-text box. I do that in the following way:
Obtain a TextRange from the FlowDocument.
Create a new FlowDocument with a smaller font using the TextRange.
Send this new FlowDocument to the printer.
My problem, is that the font doesn't seem to change. I would like it to go down to size 8. Instead, it remains at a fixed size. Here is my code:
private void button_Print_Click(object sender, RoutedEventArgs e)
{
IDocumentPaginatorSource ps = null;
FlowDocument fd = new FlowDocument();
PrintDialog pd = new PrintDialog();
Paragraph pg = new Paragraph();
Style style = new Style(typeof(Paragraph));
Run r = null;
string text = string.Empty;
// get the text
text = new TextRange(
this.richTextBox_Info.Document.ContentStart,
this.richTextBox_Info.Document.ContentEnd).Text;
// configure the style of the flow document
style.Setters.Add(new Setter(Block.MarginProperty, new Thickness(0)));
fd.Resources.Add(typeof(Paragraph), style);
// style the paragraph
pg.LineHeight = 0;
pg.LineStackingStrategy = LineStackingStrategy.BlockLineHeight;
pg.FontFamily = new FontFamily("Courier New");
pg.TextAlignment = TextAlignment.Left;
pg.FontSize = 8;
// create the paragraph
r = new Run(text);
r.FontFamily = new FontFamily("Courier New");
r.FontSize = 8;
pg.Inlines.Add(r);
// add the paragraph to the document
fd.Blocks.Add(pg);
ps = fd;
// format the page
fd.PagePadding = new Thickness(50);
fd.ColumnGap = 0;
fd.ColumnWidth = pd.PrintableAreaWidth;
// print the document
if (pd.ShowDialog().Value == true)
{
pd.PrintDocument(ps.DocumentPaginator, "Information Box");
}
}
I would like to add that, changing the font works just fine for the flow-document when it is inside of the rich-text box. However, when I am doing it programmatically (as shown above) I run into problems.
I try your code and found when I remove this line and then change the r.FontSize to 50, it seems work.
pg.LineHeight = 0;
I am printing plain text in WPF by using a FlowDocument, FlowDocumentPaginator and PrintDialog. My approach is based on this article and is implemented as follows:
var printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
{
var flowDocument = new FlowDocument();
var paragraph = new Paragraph();
paragraph.FontFamily = new FontFamily("Courier New");
paragraph.FontSize = 10;
paragraph.Margin = new Thickness(0);
paragraph.Inlines.Add(new Run(this.textToPrint));
flowDocument.FontSize = 10;
flowDocument.Blocks.Add(paragraph);
var paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
printDialog.PrintDocument(paginator, "Chit");
}
This works good for printing stuff with narrow width. But when I try to print a long string, it all gets stuffed in a small area:
I checked dimensions in the print dialog's PrintTicket and in the paginator, and they seem to be okay:
So, what is causing this problem and how can I fix it?
This is some code I use
flowDocument.PagePadding = new Thickness(standardThickness);
flowDocument.ColumnGap = 0;
flowDocument.ColumnWidth = printDialog.PrintableAreaWidth;
You need to tell the flowdocument it is one column and tell the flowdocument the width of the printer.
I have a class that build the content for my table of contents and that works, fine and dandy.
Here's the code:
public void Build(string center,IDictionary<string,iTextSharp.text.Image> images)
{
iTextSharp.text.Image image = null;
XPathDocument rapportTekst = new XPathDocument(Application.StartupPath + #"..\..\..\RapportTemplates\RapportTekst.xml");
XPathNavigator nav = rapportTekst.CreateNavigator();
XPathNodeIterator iter;
iter = nav.Select("//dokument/brevhoved");
iter.MoveNext();
var logo = iTextSharp.text.Image.GetInstance(iter.Current.GetAttribute("url", ""));
iter = nav.Select("//dokument/gem_som");
iter.MoveNext();
string outputPath = iter.Current.GetAttribute("url", "")+center+".pdf";
iter = nav.Select("//dokument/titel");
iter.MoveNext();
this.titel = center;
Document document = new Document(PageSize.A4, 30, 30, 100, 30);
var outputStream = new FileStream(outputPath, FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document, outputStream);
pdfWriter.SetLinearPageMode();
var pageEventHandler = new PageEventHandler();
pageEventHandler.ImageHeader = logo;
pdfWriter.PageEvent = pageEventHandler;
DateTime timeOfReport = DateTime.Now.AddMonths(-1);
pageWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
pageHight = document.PageSize.Height - (document.TopMargin + document.BottomMargin);
document.Open();
var title = new Paragraph(titel, titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
List<TableOfContentsEntry> _contentsTable = new List<TableOfContentsEntry>();
nav.MoveToRoot();
iter = nav.Select("//dokument/indhold/*");
Chapter chapter = null;
int chapterCount = 1;
while (iter.MoveNext())
{
_contentsTable.Add(new TableOfContentsEntry("Test", pdfWriter.CurrentPageNumber.ToString()));
XPathNodeIterator innerIter = iter.Current.SelectChildren(XPathNodeType.All);
chapter = new Chapter("test", chapterCount);
while(innerIter.MoveNext())
{
if (innerIter.Current.Name.ToString().ToLower().Equals("billede"))
{
image = images[innerIter.Current.GetAttribute("navn", "")];
image.Alignment = Image.ALIGN_CENTER;
image.ScaleToFit(pageWidth, pageHight);
chapter.Add(image);
}
if (innerIter.Current.Name.ToString().ToLower().Equals("sektion"))
{
string line = "";
var afsnit = new Paragraph();
line += (innerIter.Current.GetAttribute("id", "") + " ");
innerIter.Current.MoveToFirstChild();
line += innerIter.Current.Value;
afsnit.Add(line);
innerIter.Current.MoveToNext();
afsnit.Add(innerIter.Current.Value);
chapter.Add(afsnit);
}
}
chapterCount++;
document.Add(chapter);
}
document = CreateTableOfContents(document, pdfWriter, _contentsTable);
document.Close();
}
I'm then calling the method CreateTableOfContents(), and as such it is doing what it is supposed to do. Here's the code for the method:
public Document CreateTableOfContents(Document _doc, PdfWriter _pdfWriter, List<TableOfContentsEntry> _contentsTable)
{
_doc.NewPage();
_doc.Add(new Paragraph("Table of Contents", FontFactory.GetFont("Arial", 18, Font.BOLD)));
_doc.Add(new Chunk(Environment.NewLine));
PdfPTable _pdfContentsTable = new PdfPTable(2);
foreach (TableOfContentsEntry content in _contentsTable)
{
PdfPCell nameCell = new PdfPCell(_pdfContentsTable);
nameCell.Border = Rectangle.NO_BORDER;
nameCell.Padding = 6f;
nameCell.Phrase = new Phrase(content.Title);
_pdfContentsTable.AddCell(nameCell);
PdfPCell pageCell = new PdfPCell(_pdfContentsTable);
pageCell.Border = Rectangle.NO_BORDER;
pageCell.Padding = 6f;
pageCell.Phrase = new Phrase(content.Page);
_pdfContentsTable.AddCell(pageCell);
}
_doc.Add(_pdfContentsTable);
_doc.Add(new Chunk(Environment.NewLine));
/** Reorder pages so that TOC will will be the second page in the doc
* right after the title page**/
int toc = _pdfWriter.PageNumber - 1;
int total = _pdfWriter.ReorderPages(null);
int[] order = new int[total];
for (int i = 0; i < total; i++)
{
if (i == 0)
{
order[i] = 1;
}
else if (i == 1)
{
order[i] = toc;
}
else
{
order[i] = i;
}
}
_pdfWriter.ReorderPages(order);
return _doc;
}
The problem is however. I want to insert a page break before the table of contents, for the sake of reordering the pages, so that the table of contents is the first page, naturally. But the output of the pdf-file is not right.
Here's a picture of what it looks like:
It seems like the _doc.NewPage() in the CreateTableOfContents() method does not execute correctly. Meaning that the image and the table of contents is still on the same page when the method starts the reordering of pages.
EDIT: To clarify the above, the _doc.NewPage() gets executed, but the blank page is added after the picture and the table of contents.
I've read a couple of places that this could be because one is trying to insert a new page after an already blank page. But this is not the case.
I'll just link to the pdf files aswell, to better illustrate the problem.
The pdf with table of contents: with table of contents
The pdf without table of contents: without table of contents
Thank you in advance for your help :)