IronPdf Print to Margin - c#

I try to print a pdf with IronPdf from html but the result leaves a border.
Is there a way to set Fit-To-Page in my PrintDocument?
Here my code:
public static void PrintDocument(string printer, bool landscape, PdfDocument pdfDocument, Duplexing duplex)
{
var printDocument = pdfDocument.GetPrintDocument();
printDocument.PrinterSettings.PrinterName = printer;
printDocument.DefaultPageSettings.Landscape = landscape;
printDocument.PrinterSettings.Duplex = DuplexMapping(duplex);
printDocument.PrinterSettings.DefaultPageSettings.PaperSize.RawKind = (int)PaperKind.A4;
printDocument.Print();
}

Thanks to IronPdf-Support I found a solution:
// enable javascript
var renderer = new IronPdf.HtmlToPdf();
renderer.PrintOptions.EnableJavaScript = true;
renderer.PrintOptions.RenderDelay = 500; //milliseconds
renderer.PrintOptions.CssMediaType = IronPdf.PdfPrintOptions.PdfCssMediaType.Screen;
renderer.PrintOptions.MarginTop = 0;
renderer.PrintOptions.MarginBottom = 0;
renderer.PrintOptions.MarginLeft = 0;
renderer.PrintOptions.MarginRight = 0;
Set Margin to 0.

Related

PdfSharpCore/MigraDocCore how can add a background image

I want to create invoices with PdfSharpCore. that also works very well.
I would like to add a background image for each page. Can someone help me here?
With this code I can insert a background image after the document is created.
CreateDocument();
PdfDocumentRenderer renderer = new(true)
{
Document = Pdf
};
if (!string.IsNullOrWhiteSpace(Invoice.BackgroundImage))
{
renderer.PrepareRenderPages();
int pages = renderer.DocumentRenderer.FormattedDocument.PageCount;
var background = XImage.FromStream(() => {
return System.IO.File.OpenRead(Invoice.BackgroundImage);
});
for (int i = 1; i <= pages; ++i)
{
PageInfo pageInfo = renderer.DocumentRenderer.FormattedDocument.GetPageInfo(i);
PdfPage page = renderer.PdfDocument.AddPage();
var gfx = XGraphics.FromPdfPage(page, XPageDirection.Downwards);
gfx.DrawImage(background, 0, 0, pageInfo.Width, pageInfo.Height);
renderer.DocumentRenderer.RenderPage(gfx, i);
}
}
else
renderer.RenderDocument();
if (!string.IsNullOrEmpty(password))
SetPassword(renderer, password);
renderer.PdfDocument.Save(filename);

How to send a shape to front in Aspose.Words

I am placing a watermark on a Document, but sometimes the watermark ends up behind some image and I can't bring it to front. I tried to set the ZOrderPosition and ZOrder property to high values like 99 but it still not in front of everything else.
The problem occurs because watermark shape resides inside header footer story of Word document and main content is inside body story (please see Story class). If you insert a watermark using Microsoft Word 2016, you will observe the same behavior. All content of document's header/footer is always behind the main content of the document.
However, you may overcome this problem by manually inserting watermarks in each Page. You can achieve this by moving the cursor to the first Run in each Page of your document and then making those Runs as an anchor points for your watermarks. Please see the following code for example:
Document doc = new Document(MyDir + #"input.doc");
Node[] runs = doc.GetChildNodes(NodeType.Run, true).ToArray();
for (int i = 0; i < runs.Length; i++)
{
Run run = (Run)runs[i];
int length = run.Text.Length;
Run currentNode = run;
for (int x = 1; x < length; x++)
{
currentNode = SplitRun(currentNode, 1);
}
}
DocumentBuilder builder = new DocumentBuilder(doc);
PageSetup ps = builder.PageSetup;
NodeCollection smallRuns = doc.GetChildNodes(NodeType.Run, true);
LayoutCollector collector = new LayoutCollector(doc);
int pageIndex = 1;
foreach (Run run in smallRuns)
{
if (collector.GetStartPageIndex(run) == pageIndex)
{
Shape watermark = new Shape(doc, Aspose.Words.Drawing.ShapeType.TextPlainText);
watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
watermark.Width = 300;
watermark.Height = 70;
watermark.HorizontalAlignment = HorizontalAlignment.Center;
watermark.VerticalAlignment = VerticalAlignment.Center;
watermark.Rotation = -40;
watermark.Fill.Color = Color.Gray;
watermark.StrokeColor = Color.Gray;
watermark.TextPath.Text = "watermarkText";
watermark.TextPath.FontFamily = "Arial";
watermark.Name = string.Format("WaterMark_{0}", Guid.NewGuid());
watermark.WrapType = WrapType.None;
builder.MoveTo(run);
builder.InsertNode(watermark);
pageIndex++;
}
}
doc.Save(MyDir + #"output\18.3.doc");
///////////////////////////////////////
private static Run SplitRun(Run run, int position)
{
Run afterRun = (Run)run.Clone(true);
afterRun.Text = run.Text.Substring(position);
run.Text = run.Text.Substring((0), (0) + (position));
run.ParentNode.InsertAfter(afterRun, run);
return afterRun;
}
Hope, this helps. I work with Aspose as Developer Evangelist.

Aspose.Word page number in right margin

i build document with Aspose.Word. I try add page number in right margin. Image better explain it:
My result pdf preview
How to do it?
My current code:
var document = new Document();
_builder = new DocumentBuilder(document)
{
PageSetup =
{
Orientation = Orientation.Portrait,
PaperSize = PaperSize.A4,
RightMargin = ConvertUtil.MillimeterToPoint(20),
BottomMargin = ConvertUtil.MillimeterToPoint(35),
LeftMargin = ConvertUtil.MillimeterToPoint(35),
TopMargin = ConvertUtil.MillimeterToPoint(35)
}
};
_builder.StartTable();
_builder.InsertCell();
_builder.Write("Test test test");
_builder.EndTable();
_builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
_builder.Write("Pages: ");
_builder.InsertField("PAGE", "");
_builder.Write("/");
_builder.InsertField("NUMPAGES");
document.Save(stream, SaveFormat.Pdf);
In your case, you need to add text box in the footer of document, insert page number field in it, and set its position. Please use following modified code example to get the desired output.
var document = new Document();
DocumentBuilder _builder = new DocumentBuilder(document)
{
PageSetup =
{
Orientation = Orientation.Portrait,
PaperSize = Aspose.Words.PaperSize.A4,
RightMargin = ConvertUtil.MillimeterToPoint(20),
BottomMargin = ConvertUtil.MillimeterToPoint(35),
LeftMargin = ConvertUtil.MillimeterToPoint(35),
TopMargin = ConvertUtil.MillimeterToPoint(35)
}
};
_builder.StartTable();
_builder.InsertCell();
_builder.Write("Test test test");
_builder.EndTable();
_builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
Shape shape = new Shape(document, ShapeType.TextBox);
shape.Stroked = false;
shape.Width = _builder.CurrentSection.PageSetup.PageWidth;
shape.Height = 50;
shape.Left = 0;
shape.Left = - _builder.CurrentSection.PageSetup.LeftMargin;
shape.Top = 0;
Paragraph paragraph = new Paragraph(document);
shape.AppendChild(paragraph);
_builder.InsertNode(shape);
_builder.MoveTo(paragraph);
_builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
_builder.Write("Pages: ");
_builder.InsertField("PAGE", "");
_builder.Write("/");
_builder.InsertField("NUMPAGES");
document.Save(MyDir + "output.pdf", SaveFormat.Pdf);
I work with Aspose as Developer evangelist.

Printing a stackpanel containing a listbox over multiple pages wpf

Hi I am looking to print a StackPanel that contains a listbox which can contain an infinite number of items and therefore needs to print over multiple pages. I found this code online and it works fine.
public static FixedDocument GetFixedDocument(FrameworkElement toPrint, PrintDialog printDialog)
{
if (printDialog == null)
{
printDialog = new PrintDialog();
}
var capabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
var pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
var visibleSize = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
var fixedDoc = new FixedDocument();
//If the toPrint visual is not displayed on screen we neeed to measure and arrange it
toPrint.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
toPrint.Arrange(new Rect(new Point(0, 0), toPrint.DesiredSize));
//
var size = toPrint.DesiredSize;
//Will assume for simplicity the control fits horizontally on the page
double yOffset = 0;
while (yOffset < size.Height)
{
var vb = new VisualBrush(toPrint)
{
Stretch = Stretch.None,
AlignmentX = AlignmentX.Left,
AlignmentY = AlignmentY.Top,
ViewboxUnits = BrushMappingMode.Absolute,
TileMode = TileMode.None,
Viewbox = new Rect(0, yOffset, visibleSize.Width, visibleSize.Height)
};
var pageContent = new PageContent();
var page = new FixedPage();
((IAddChild)pageContent).AddChild(page);
fixedDoc.Pages.Add(pageContent);
page.Width = pageSize.Width;
page.Height = pageSize.Height;
var canvas = new Canvas();
FixedPage.SetLeft(canvas, capabilities.PageImageableArea.OriginWidth);
FixedPage.SetTop(canvas, capabilities.PageImageableArea.OriginHeight);
canvas.Width = visibleSize.Width;
canvas.Height = visibleSize.Height;
canvas.Background = vb;
page.Children.Add(canvas);
yOffset += visibleSize.Height;
}
return fixedDoc;
}
However this causes certain items of a listbox to be cut off at the bottom of a page and continued on the next page (as shown below). Is it possible to modify this code in any way to determine the size of the page and if the current listboxitem does not fit onto this page that it starts on the next page? Quite new to all this so any help would be greatly appreciated.
I had a similiar task once and came up with this code, which uses a 'dummy' renderer to determine the height of the element up front and then either adds it to the current page or creates a new one. For sure, that's not a very beautiful solution, but it did the job at the time. Maybe you can take sth. away from it.
Size A4Size = new Size(793.92, 1122.24);
Size InfiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
var pages = new List<FrameworkElement>();
int pageNumber = 0;
var printDate = DateTime.Now;
var size = A4Size;
var currentPage = new Report(size, printDate);
currentPage.Render();
var listElements = new Queue<ElementsToPrint>(...);
var dummyRenderer = new Viewbox();
dummyRenderer.Child = currentPage;
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
var template = (DataTemplate)View.FindResource("ItemTemplate");
dummyRenderer.Child = null;
var availableHeight = currentPage.View.ActualHeight;
while (listElements.Count > 0)
{
var elementToRender = listElements.Dequeue();
dummyRenderer.Child = new ListViewItem()
{
Content = elementToRender,
ContentTemplate = template,
Foreground = Brushes.Black
};
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
var renderedItem = (ListViewItem)dummyRenderer.Child;
dummyRenderer.Child = null;
var willItFit = availableHeight > renderedItem.ActualHeight;
if (willItFit)
{
currentPage.DataListView.Items.Add(renderedItem);
availableHeight -= renderedItem.ActualHeight;
}
else
{
dummyRenderer.Child = currentPage;
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
dummyRenderer.Child = null;
pages.Add(currentPage);
// Set up a new Page
pageNumber++;
currentPage = new DiaryReport(size,pageNumber,printDate,anonymous);
dummyRenderer.Child = currentPage;
dummyRenderer.Measure(InfiniteSize);
dummyRenderer.Arrange(new Rect(dummyRenderer.DesiredSize));
dummyRenderer.UpdateLayout();
dummyRenderer.Child = null;
availableHeight = currentPage.DataListView.ActualHeight;
currentPage.DataListView.Items.Add(renderedItem);
availableHeight -= renderedItem.ActualHeight;
}

How to get FontSize from an Adobe Illustrator (.ai) TextFrame using C#?

I'm successfully reading an Adobe Illustrator file using Adobe Illustrator Library in C# but I can't get the FontSize for a TextFrame. Can Anyone help? Below is the code I've used:
Illustrator.Application aiApp = new Illustrator.Application();
Illustrator.Document doc = aiApp.Open(#"K:\test\test.ai",Illustrator.AiDocumentColorSpace.aiDocumentRGBColor, null);
List<Label> _labela = new List<Label>();
int cntr = 0;
foreach (TextFrame tf in doc.TextFrames)
{
_labela.Add(new Label());
// caktojme vetite per secilen label
_labela[cntr].Name = "lblTextFrame" + cntr;
_labela[cntr].AutoSize = true;
_labela[cntr].Text = tf.Contents;
_labela[cntr].ForeColor = Color.FromArgb((int)tf.Layer.Color.Red, (int)tf.Layer.Color.Green, (int)tf.Layer.Color.Blue);
_labela[cntr].Top = Math.Abs((int)tf.Top);
_labela[cntr].Left = Math.Abs((int)tf.Left);
cntr++;
}
foreach (Label lbl in _labela)
{
//lbl.BackColor = Color.Black;
this.Controls.Add(lbl);
this.SuspendLayout();
this.Refresh();
}
}
I don't see any properties for TextFrame.FontSize ??? :( . Any suggestions!?
You read the font name & size like this
for (int i = 1; i <= doc.TextFrames.Count; i++)
{
Illustrator.TextFrame tF = doc.TextFrames[i];
Illustrator.TextFont objFont = tF.TextRange.CharacterAttributes.TextFont;
double size = tF.TextRange.CharacterAttributes.Size;
Console.WriteLine("Size: {0}, FontName: {1})", size, objFont.Name);
}

Categories