Adding picture to footer of a word document - c#

I have a problem with my program. I need to add a picture in the footer of a word document.
I have 2 functions, replacing bookmarked text and add images. The replace bookmarked text works. add images doesnt work, i searched for days on stackoverflow, but i cant find any sollution. I hope someone can help me out.
private static void AddImages(Document wordDoc, string imagePath){
var sec = wordDoc.Application.Selection.Sections[1];
var ft = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
var rngFooter = ft.Range;
object oRange = rngFooter;
var autoScaledInlineShape = ft.Shapes.AddPicture(imagePath);
var scaledWidth = autoScaledInlineShape.Width;
var scaledHeight = autoScaledInlineShape.Height;
autoScaledInlineShape.Delete();
// Create a new Shape and fill it with the picture
var newShape = wordDoc.Shapes.AddShape(1, 0, 0, scaledWidth, scaledHeight);
newShape.Fill.UserPicture(imagePath);
// Convert the Shape to an InlineShape and optional disable Border
var finalInlineShape = newShape.ConvertToInlineShape();
finalInlineShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
// Cut the range of the InlineShape to clipboard
finalInlineShape.Range.Cut();
// And paste it to the target Range
ft.Paste();
}

Found sollution
private static void FindAndReplaceImages(Document wordDoc, string imagePath){
var sec = wordDoc.Application.Selection.Sections[1];
foreach (Section wordSection in wordDoc.Sections)
{
var footer = sec.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
var footerImage = footer.Shapes.AddShape(1, 0, 0, 594, 280);
footerImage.Fill.UserPicture(imagePath);
footerImage.WrapFormat.Type = WdWrapType.wdWrapThrough;
footerImage.WrapFormat.AllowOverlap = -1;
footerImage.WrapFormat.Side = WdWrapSideType.wdWrapBoth;
footerImage.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
footerImage.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
footerImage.Top = (float)561.2;
}
}

Related

C# GemBox How to get the position of a TextBox or Shape

I was wondering how I can get the position of a TextBox or a Shape inside the GemBox DLL.
This is my TextBox:
var textBox1 = new TextBox(document, Layout.Floating(
new HorizontalPosition(15, LengthUnit.Pixel, HorizontalPositionAnchor.TopLeftCorner),
new VerticalPosition(70, LengthUnit.Pixel, VerticalPositionAnchor.TopLeftCorner),
new Size(pageSetup.PageWidth - 175, 100, LengthUnit.Point)),
ShapeType.RoundedRectangle);
textBox1.AdjustValues["adj"] = 5000;
textBox1.Outline.Fill.SetEmpty();
textBox1.Fill.SetSolid(Color.White);
Now I want to get access to the Horizontal and Vertical position.
Thanks for any help.
Use this:
if (textBox1.Layout.IsFloating)
{
var layout = (FloatingLayout)textBox1.Layout;
var horizontalPosition = layout.HorizontalPosition;
var verticalPosition = layout.VerticalPosition;
// ...
}

Center footer PDF using SelectPdf .NET

Hi i'm using SelectPdf for Net Core.
First i generate a method for convert html content to pdf, then i configure my pdf options and finally i add footer in all pages, this work but I can't find any property to center my footer in the document.
public string _htmlStringToBase64(string htmlContent)
{
HtmlToPdf converter = new HtmlToPdf();
converter.Options.PdfPageSize = PdfPageSize.A4;
converter.Options.DisplayFooter = true;
converter.Footer.DisplayOnFirstPage = true;
converter.Footer.DisplayOnOddPages = true;
converter.Footer.DisplayOnEvenPages = true;
converter.Footer.Height = 80;
converter.Options.MarginLeft = 20;
converter.Options.MarginRight = 20;
converter.Options.MarginBottom = 30;
converter.Options.MarginTop = 15;
//this footer options
PdfHtmlSection footerHtml = new PdfHtmlSection(ExternalResources.FooterBase64Img);
footerHtml.AutoFitHeight = HtmlToPdfPageFitMode.ShrinkOnly;
footerHtml.CustomCSS = "text-align: center;"; //I tried that but it doesn't work
converter.Footer.Add(footerHtml);
var docPDF = converter.ConvertHtmlString(htmlContent);
MemoryStream stream = new MemoryStream();
docPDF.Save(stream);
docPDF.Close();
return Convert.ToBase64String(stream.ToArray())
}
As I said, the footer unfolds without problems but I need to center it
The constructor of the PdfHtmlSection class has several overloads, one of them allows the X, Y axes and the url of the image.
You can try assigning a value to the X axis which is the one that aligns horizontally, you can try the following code:
PdfHtmlSection footerHtml = new PdfHtmlSection(100, 0,ExternalResources.FooterBase64Img);
where the 100 value is the position offset from left
the next url show all properties: https://selectpdf.com/docs/Overload_SelectPdf_PdfHtmlSection__ctor.htm

UISearchBar not resizing on phone rotation

I am having an issue where my UISearchBar does not resize on phone rotation unless I touch on the search bar so that it has focus (see images below).
The search bar is created and added to a UIMapView as a subview. See code.
Searchbar creation:
public UISearchController DefineSearchController()
{
_searchResultsController = new SearchResultsVC(_mapView);
_searchResultsController.searchItemSelected += PlaceSelect;
_searchUpdater = new SearchResultsUpdator();
_searchUpdater.UpdateSearchResults += _searchResultsController.Search;
//add the search controller
var searchController = new UISearchController(_searchResultsController)
{
SearchResultsUpdater = _searchUpdater
};
var scb = searchController.SearchBar;
scb.SizeToFit();
scb.SearchBarStyle = UISearchBarStyle.Minimal;
var img = UIImage.FromBundle("tabSpace");
scb.SetBackgroundImage(img, UIBarPosition.Top, UIBarMetrics.Default);
var textField = scb.ValueForKey(new NSString("searchField")) as UITextField;
if (textField != null)
{
var backgroundView = textField.Subviews[0];
if (backgroundView != null)
{
backgroundView.BackgroundColor = UIColor.White;
backgroundView.Layer.BorderColor = AppColour.PersianBlue.GetUIColour().CGColor;
backgroundView.Layer.BorderWidth = 1;
backgroundView.Layer.CornerRadius = 10;
backgroundView.ClipsToBounds = true;
}
}
var localEnterPoI = NSBundle.MainBundle.LocalizedString("placeHolderSearchForLocation", "Enter a PoI to search for");
scb.Placeholder = localEnterPoI;
searchController.Delegate = new SearchControllerDelegate();
searchController.HidesNavigationBarDuringPresentation = false;
return searchController;
}
Added to the subview:
//Define Search Controller
_mapSearchManager = new MapSearchManager(_mapView);
_searchController = _mapSearchManager.DefineSearchController();
var scb = _searchController.SearchBar;
_mapView.AddSubview(scb);
NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{
scb.TopAnchor.ConstraintEqualTo(_mapView.TopAnchor, 30),
scb.LeadingAnchor.ConstraintEqualTo(_mapView.LeadingAnchor, 10),
scb.TrailingAnchor.ConstraintEqualTo(_mapView.LeadingAnchor, -10),
});
I heave search extensively and was only able to find one similar issue:
UISearchBar doesn't resize when frame is resized in IOS 11
I implementing both of suggestion but it didn't make any difference.
Has anyone else encounted this or know what a possible solution might be.
Cheers

Get a WPF RichTextBox to draw a horizontal line over text

Say I have a given TextRange range that happens to have this text in it ----------------- (On its own line.)
I want to draw a real line whenever I see that text (instead of just 15 dashes).
But, I need to leave the dashes there for when I save it (and when other, plain text viewers load it).
I found how I can draw a line in the RichTextBox:
var line = new Line {X1 = 10, X2 = 200, Y1 = 5, Y2 = 5,
var paragraph = (Paragraph) MyRichTextBox.Document.Blocks.FirstBlock;
paragraph.Inlines.Add(line);
But this just draw after the last Inline in the paragraph.
So, my question is:
How can I draw so that my UIElement does not have text wrapping on (so that I can cover the dashes)?
Is this possible with the WPF RichTextBox?
Could you use "TextDecorations.Strikethrough" for this.
TextRange range = new TextRange(RichTextBox.Selection.Start, RichTextBox.Selection.End);
TextDecorationCollection tdc = (TextDecorationCollection)RichTextBox.Selection.GetPropertyValue(Inline.TextDecorationsProperty);
if (!tdc.Equals(TextDecorations.Strikethrough))
{
tdc = TextDecorations.Strikethrough;
}
range.ApplyPropertyValue(Inline.TextDecorationsProperty, tdc);
I think you have to remove the Inline from within the paragraph and replace it with a Line element. In this case, you will have to replace Line elements with "-----" on save.
private void FindHRules()
{
foreach (Paragraph block in rtf.Document.Blocks.OfType<Paragraph>())
{
var inlines = block.Inlines.ToList();
for(int i = 0; i<inlines.Count; i++)
{
var inline = inlines[i];
TextRange r = new TextRange(inline.ContentStart, inline.ContentEnd);
if (r.Text.StartsWith("--"))
{
Line l = new Line { Stretch = Stretch.Fill, Stroke = Brushes.DarkBlue, X2 = 1 };
block.Inlines.InsertAfter(inline, new InlineUIContainer(l));
block.Inlines.Remove(inline);
}
}
}
}
I tested this with a RTF doc that had the "-----" lines in stand-alone paragraphs (<enter>) and line breaks (<shift-enter>) within other paragraphs.

(Composite) Geometry confusion in c#

I'm trying to create 1 complex composite shape on an InkCanvas, but I must be doing something wrong, as what I was expecting to happen, is not. I've tried several different incarnations of accomplishing this.
So I have this method.
private void InkCanvas_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
{
Stroke stroke = e.Stroke;
// Close the "shape".
StylusPoint firstPoint = stroke.StylusPoints[0];
stroke.StylusPoints.Add(new StylusPoint() { X = firstPoint.X, Y = firstPoint.Y });
// Hide the drawn shape on the InkCanvas.
stroke.DrawingAttributes.Height = DrawingAttributes.MinHeight;
stroke.DrawingAttributes.Width = DrawingAttributes.MinWidth;
// Add to GeometryGroup. According to http://msdn.microsoft.com/en-us/library/system.windows.media.combinedgeometry.aspx
// a GeometryGroup should work better at Unions.
_revealShapes.Children.Add(stroke.GetGeometry());
Path p = new Path();
p.Stroke = Brushes.Green;
p.StrokeThickness = 1;
p.Fill = Brushes.Yellow;
p.Data = _revealShapes.GetOutlinedPathGeometry();
selectionInkCanvas.Children.Clear();
selectionInkCanvas.Children.Add(p);
}
But this is what I get:
http://img72.imageshack.us/img72/1286/actual.png
So where am I going wrong?
TIA,
Ed
The problem is that the Geometry returned by stroke.GetGeometry() is a path around the stroke, so the area you're filling with yellow is just the middle of the stroke. You can see this more clearly if you make the lines thicker:
_revealShapes.Children.Add(stroke.GetGeometry(new DrawingAttributes() { Width = 10, Height = 10 }));
You can do what you want if you convert the list of stylus points to a StreamGeometry yourself:
var geometry = new StreamGeometry();
using (var geometryContext = geometry.Open())
{
var lastPoint = stroke.StylusPoints.Last();
geometryContext.BeginFigure(new Point(lastPoint.X, lastPoint.Y), true, true);
foreach (var point in stroke.StylusPoints)
{
geometryContext.LineTo(new Point(point.X, point.Y), true, true);
}
}
geometry.Freeze();
_revealShapes.Children.Add(geometry);

Categories

Resources