I'm sure it's something stupid I'm doing but I can't figure it out. I'm trying to write a KML from scratch. It will be inside a KMZ with a bunch of georeferenced pictures that I won't to show up as photo overlays. I can't get it to write a KML though, I find the documentation too basic to incorporate a Folder. When I pause the program and debug, it shows Kml kml as having no children, but the feature 'folder' has 42. And then the namespaces aren't showing up, and it's not writing the Kml file. Please, any help you can give me!
public void WriteKML_sharp()
{
Kml kml = new Kml();
kml.AddNamespacePrefix(KmlNamespaces.GX22Prefix, KmlNamespaces.GX22Namespace);
Folder folder = new Folder();
kml.Feature = folder;
foreach (Picture picture in _process.pictures)
{
PhotoOverlay photooverlay = new PhotoOverlay();
photooverlay.Name = picture.name + picture.extension;
photooverlay.Open = true;
photooverlay.Shape = Shape.Rectangle;
Icon icon = new Icon();
Uri uri = new Uri(Path.Combine("files", picture.name + picture.extension), UriKind.Relative);
icon.Href = uri;
photooverlay.Icon = icon;
Point point = new Point();
point.Coordinate = new Vector(picture.gpslat, picture.gpslong);
//point.Coordinate = new Vector(picture.gpslat, picture.gpslong, picture.gpsalt);
point.AltitudeMode = AltitudeMode.RelativeToGround;
photooverlay.Location = point;
ViewVolume viewvolume = new ViewVolume();
viewvolume.Top = 25;
viewvolume.Bottom = -25;
viewvolume.Left = 20;
viewvolume.Right = -20;
photooverlay.View = viewvolume;
folder.AddFeature(photooverlay);
}
KmlFile kmlfile = KmlFile.Create(kml, false);
using (var stream = System.IO.File.OpenWrite(_filename))
{
kmlfile.Save(stream);
}
}
I am not sure if this will be the reason but u can try adding a document in the KML file and assign that document as kml.Feature and Add your feature to this document using .AddFeature(folder);
It works for me that way
Related
So I am trying to convert a standard A4 PDF file into a .txt file using Spire.Pdf NuGet Package, and whenever I do it there is a lot of whitespace at the start of each line where the margins of the document go I presume. I managed to solve the issue using the TrimStart() method but I want to be able to do remove the margins using Spire.Pdf itself.
I have played around with setting a PdfTextExtractOptions ExtractArea RectangleF but for some reason it cuts the bottom of the text and I lose rows.
My code is:
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"path");
var content = new List<string>();
RectangleF rectangle = new RectangleF(45, 0, 0, 0);
PdfTextExtractOptions options = new() { IsExtractAllText = true, IsShowHiddenText = true, ExtractArea = rectangle };
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor textExtractor = new(page);
//extract text from a specific rectangular area here - defualt A4 margin sizes?
string extractedText = textExtractor.ExtractText(options);
content.Add(extractedText);
}
FileStream fs = new FileStream(#"outputFile.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
string txtBefore = (string.Join("\n", content));
sw.Write(txtBefore);
Thanks in advance
You can try the code below to extract text from PDF, it will not generate extra white spaces at the start of each line in the result .txt file. I already tested it.
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(#"test.pdf");
PdfTextExtractOptions options = new PdfTextExtractOptions();
options.IsSimpleExtraction = true;
StringBuilder sb = new StringBuilder();
foreach (PdfPageBase page in doc.Pages)
{
PdfTextExtractor extractor = new PdfTextExtractor(page);
sb.AppendLine(extractor.ExtractText(options));
}
File.WriteAllText("Extract.txt", sb.ToString());
I am trying to create a process in .NET to convert a PDF and all it's pages + attachments to PNGs. I am evaluating libraries and came across PDFiumSharp but it is not working for me. Here is my code:
string Inputfile = "input.pdf";
string OutputFolder = "Output";
string fileName = Path.GetFileNameWithoutExtension(Inputfile);
using (PdfDocument doc = new PdfDocument(Inputfile))
{
for (int i = 0; i < doc.Pages.Count; i++)
{
var page = doc.Pages[i];
using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, false))
{
page.Render(bitmap);
var targetFile = Path.Combine(OutputFolder, fileName + "_" + i + ".png");
bitmap.Save(targetFile);
}
}
}
When I run this code, I get this exception:
screenshot of exception
Does anyone know how to fix this? Also does PDFiumSharp support extracting PDF attachments? If not, does anyone have any other ideas on how to achieve my goal?
PDFium does not look like it supports extracting PDF attachments. If you want to achieve your goal, then you can take a look at another library that supports both extracting PDF attachments as well as converting PDFs to PNGs.
I am an employee of the LEADTOOLS PDF SDK which you can try out via these 2 nuget packages:
https://www.nuget.org/packages/Leadtools.Pdf/
https://www.nuget.org/packages/Leadtools.Document.Sdk/
Here is some code that will convert a PDF + all attachments in the PDF to separate PNGs in an output directory:
SetLicense();
cache = new FileCache { CacheDirectory = "cache" };
List<LEADDocument> documents = new List<LEADDocument>();
if (!Directory.Exists(OutputDir))
Directory.CreateDirectory(OutputDir);
using var document = DocumentFactory.LoadFromFile("attachments.pdf", new LoadDocumentOptions { Cache = cache, LoadAttachmentsMode = DocumentLoadAttachmentsMode.AsAttachments });
if (document.Pages.Count > 0)
documents.Add(document);
foreach (var attachment in document.Attachments)
documents.Add(document.LoadDocumentAttachment(new LoadAttachmentOptions { AttachmentNumber = attachment.AttachmentNumber }));
ConvertDocuments(documents, RasterImageFormat.Png);
And the ConvertDocuments method:
static void ConvertDocuments(IEnumerable<LEADDocument> documents, RasterImageFormat imageFormat)
{
using var converter = new DocumentConverter();
using var ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD);
ocrEngine.Startup(null, null, null, null);
converter.SetOcrEngineInstance(ocrEngine, false);
converter.SetDocumentWriterInstance(new DocumentWriter());
foreach (var document in documents)
{
var name = string.IsNullOrEmpty(document.Name) ? "Attachment" : document.Name;
string outputFile = Path.Combine(OutputDir, $"{name}.{RasterCodecs.GetExtension(imageFormat)}");
int count = 1;
while (File.Exists(outputFile))
outputFile = Path.Combine(OutputDir, $"{name}({count++}).{RasterCodecs.GetExtension(imageFormat)}");
var jobData = new DocumentConverterJobData
{
Document = document,
Cache = cache,
DocumentFormat = DocumentFormat.User,
RasterImageFormat = imageFormat,
RasterImageBitsPerPixel = 0,
OutputDocumentFileName = outputFile,
};
var job = converter.Jobs.CreateJob(jobData);
converter.Jobs.RunJob(job);
}
}
Trying to create an mp3 embedder for personal use. Tried all of the solutions here on StackO, but none have worked.
Here is what I have:
TagLib.File tagFile = TagLib.File.Create("C:\\Users\\Dom\\Desktop\\song.mp3");
TagLib.Id3v2.AttachedPictureFrame pic = new TagLib.Id3v2.AttachedPictureFrame();
pic.TextEncoding = TagLib.StringType.Latin1;
pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
pic.Type = TagLib.PictureType.FrontCover;
pic.Data = TagLib.ByteVector.FromPath("C:\\Users\\Dom\\Pictures\\picture.png");
tagFile.Tag.Pictures = new TagLib.IPicture[1] { pic };
tagFile.Tag.Album = "Album 1";
tagFile.Tag.Year = 1990;
tagFile.Save();
The album tag and year tag show up fine under properties, and the program is not crashing or throwing any errors. Picture does not show up as the file icon, or in windows media player. Picture size is 300x300 pixels if that has any importance.
The reason is probably some conflict with existing ID3v2 Tags. Fix it like this:
TagLib.File tagFile = TagLib.File.Create("C:\\Users\\Dom\\Desktop\\song.mp3");
Tag t = tagFile.GetTag(TagTypes.Id3v2);
tagFile.RemoveTags(TagTypes.Id3v2);
Tag tags = tagFile.GetTag(TagTypes.Id3v2);
tagFile.GetTag(TagTypes.Id3v2, true);
tagFile.Save();
tagFile = TagLib.File.Create("C:\\Users\\Dom\\Desktop\\song.mp3");
tags = t;
tagFile.GetTag(TagTypes.Id3v2).Pictures = new IPicture[] {
new Picture("C:\\Users\\Dom\\Pictures\\picture.png")
{ MimeType = "image/png", Type = PictureType.FrontCover }
};
tagFile.Tag.Album = "Album 1";
tagFile.GetTag(TagTypes.Id3v2).Track = 0;
tagFile.Tag.Year = 1990;
tagFile.Save();
I found some code to add an image to an Excel-sheet with the SDK 2.0. And this part works fine. Now I want a Text Box under the Image, but I don't know how to get a TextBox in general.
Which classes do I need an what is appands what or which property?
Furthermore it would be nice if it be groupt. So that when you drag one the other is following.
The code look like this (I know it's a bit much, but I couldt cut it more):
private void addImage(Offset offset, Extents extents, string sImagePath, string description)
{
WorksheetPart worksheetPart = this.arbeitsBlatt.WorksheetPart;
DrawingsPart drawingsPart;
ImagePart imagePart;
XDrSp.WorksheetDrawing worksheetDrawing;
ImagePartType imagePartType = getImageType(sImagePath);
{
// --- use the existing DrawingPart
drawingsPart = worksheetPart.DrawingsPart;
imagePart = drawingsPart.AddImagePart(imagePartType);
drawingsPart.CreateRelationshipToPart(imagePart);
worksheetDrawing = drawingsPart.WorksheetDrawing;
}
using (FileStream fileStream = new FileStream(sImagePath, FileMode.Open))
{
imagePart.FeedData(fileStream);
}
int imageNumber = drawingsPart.ImageParts.Count<ImagePart>();
if (imageNumber == 1)
{
Drawing drawing = new Drawing();
drawing.Id = drawingsPart.GetIdOfPart(imagePart);
this.arbeitsBlatt.Append(drawing);
}
XDrSp.NonVisualDrawingProperties noVisualDrawingProps = new XDrSp.NonVisualDrawingProperties();
XDrSp.NonVisualPictureDrawingProperties noVisualPictureDrawingProps = new XDrSp.NonVisualPictureDrawingProperties();
noVisualDrawingProps.Id = new UInt32Value((uint)(1024 + imageNumber));
noVisualDrawingProps.Name = "Picture " + imageNumber.ToString();
noVisualDrawingProps.Description = beschreibung;
PictureLocks picLocks = new PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
noVisualPictureDrawingProps.PictureLocks = picLocks;
XDrSp.NonVisualPictureProperties noVisualPictureProps = new XDrSp.NonVisualPictureProperties();
noVisualPictureProps.NonVisualDrawingProperties = noVisualDrawingProps;
noVisualPictureProps.NonVisualPictureDrawingProperties = noVisualPictureDrawingProps;
Stretch stretch = new Stretch();
stretch.FillRectangle = new FillRectangle();
XDrSp.BlipFill blipFill = new XDrSp.BlipFill();
Blip blip = new Blip();
blip.Embed = drawingsPart.GetIdOfPart(imagePart);
blip.CompressionState = BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new SourceRectangle();
blipFill.Append(stretch);
Transform2D t2d = new Transform2D();
t2d.Offset = offset;
t2d.Extents = extents;
XDrSp.ShapeProperties sp = new XDrSp.ShapeProperties();
sp.BlackWhiteMode = BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
PresetGeometry prstGeom = new PresetGeometry();
prstGeom.Preset = ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new AdjustValueList();
sp.Append(prstGeom);
sp.Append(new NoFill());
XDrSp.Picture picture = new XDrSp.Picture();
picture.NonVisualPictureProperties = noVisualPictureProps;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
XDrSp.OneCellAnchor anchor = this.getCellAnchor();
XDrSp.Extent extent = new XDrSp.Extent();
extent.Cx = extents.Cx;
extent.Cy = extents.Cy;
anchor.Extent = extent;
anchor.Append(picture);
anchor.Append(new XDrSp.ClientData());
worksheetDrawing.Append(anchor);
worksheetDrawing.Save(drawingsPart);
#endregion
}
I think you are new to OpenXml SDK
First of all you need to use the newest version of Open XMl SDK - Version 2.5 [Download - http://www.microsoft.com/en-us/download/details.aspx?id=30425]
Here download BOTH OpenXMLSDKV25.msi , OpenXMLSDKToolV25.msi .. Install BOTH.
Now here is the trick, OpenXML productivity tool is the one you need here. It allows you to brows an existing Excel file and break it down to CODES [watch here - https://www.youtube.com/watch?v=KSSMLR19JWA]
Now what you need to do is create an Excel sheet manually with what you want [In your case add Text Box under the Image] Then open this Excel file with productivity tool and understand the CODE . Note that you will need to understand Spreadsheet file structure to understand this CODE [ Reffer this - https://www.google.com/#q=open+xml+sdk] .. Now write your codes to meet your requirement using codes of Productivity tool
NOTE - Once you analyse the dummy Spreadsheet with Productivity tool you will understand why giving or guiding with CODE examples as an answer is not practical.
- Happy Coding-
I have been trying for long but no success i have an existing pdf that i wan to load to my current C# app and want to create a simpe pusbutton to it , plaese cite some working code the default directory of the pdf is "C:\abc.pdf".
I am using itextsharp, C# VS 2010
Thanks
The closest solution I can find is something like the following.
static void AddPushbuttonField(string inputFile, iTextSharp.text.Rectangle buttonPosition, string buttonName, string outputFile)
{
using (PdfStamper stamper = new PdfStamper(new PdfReader(inputFile), File.Create(outputFile)))
{
PushbuttonField buttonField = new PushbuttonField(stamper.Writer, buttonPosition, buttonName);
stamper.AddAnnotation(buttonField.Field, 1);
stamper.Close();
}
}
This came from here, but was not ranked up as a solution. The code looks good and based on my experience with itextsharp I think this will do the trick.
Source:
Adding button in a pdf file using iTextSharp
Rectangle _rect;
_rect = new Rectangle(50, 100, 100, 100);
PushbuttonField button = new PushbuttonField(writer, _rect, "button");
PdfAnnotation widget = button.Field;
button.BackgroundColor = new GrayColor(0.75f);
button.BorderColor = GrayColor.GRAYBLACK;
button.BorderWidth = 1;
button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED;
button.TextColor = GrayColor.GRAYBLACK;
button.FontSize = 11;
button.Text = "Text";
button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT;
button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS;
button.ProportionalIcon = true;
button.IconHorizontalAdjustment = 0;