Images.png Manipulation to SVG in C# - c#

iam using Imagemagick & potrace in c# to convert png to pnm and then to svg but unfortunately the SVG File comes with out colour!
how i can solve the colour problem? should i use another converter? suggestions please?
i have tried many packages in visual studio with C# but either don't work or the output comes out with the copyright sentence and that doesn't make my svg file nice!
i want my output with out the copyright sentence please!

You can use Aspose.Imaging for .NET API. Please open the NuGet package manager, search for "Aspose.Imaging " and install it.
Tip: I am using .net 5.0
The modified code is as follows:
using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Png;
using Aspose.Imaging.ImageOptions;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Picture
{
public static void Main()
{
string templatesFolder = #"C:\Users\Administrator\Downloads\"; //the document you want to store
string dataDir = templatesFolder;
ProcessConvertion();
void ProcessConvertion()
{
//Get list of supported formats in
//Aspose.Imaging for loading and saving images
var formats = GetAvailableImageFormats();
var importFormats = formats.Import;
var exportFormats = formats.Export;
//Process each raster and vector format that can be loaded
foreach (var format in importFormats)
{
string formatExt = format.Key;
var inputFile = #"C:\Users\Administrator\Downloads\1.png"; //your PNG of picture path
//Process each raster and vector format
//to which we can save imported image
foreach (var exportFormat in exportFormats)
{
var outputFile = Path.Combine(templatesFolder, $"convert-{formatExt}-to-{exportFormat.Key}.{exportFormat.Key}");
System.Console.WriteLine("Processing conversion:" + outputFile);
//More about load method can be found at
//https://apireference.aspose.com/imaging/net/aspose.imaging.image/load/methods/2
//Load imported image
using (var image = Image.Load(inputFile))
{
//Obtain default saving options defined for each image
ImageOptionsBase exportOptions = exportFormat.Value.Clone();
//If loaded image is vector, need to specify vector rasterization options
//for export to another vector
if (image is VectorImage)
{
VectorRasterizationOptions rasterizationOptions = format.Value;
rasterizationOptions.PageWidth = image.Width;
rasterizationOptions.PageHeight = image.Height;
exportOptions.VectorRasterizationOptions = rasterizationOptions;
}
if (Path.GetExtension(outputFile).Equals(".svg"))
{
image.Save(outputFile, exportOptions);
}
}
//File.Delete(outputFile);
}
break;
//System.GC.Collect();
}
}
(Dictionary<string, VectorRasterizationOptions> Import, Dictionary<string, ImageOptionsBase> Export) GetAvailableImageFormats()
{
///Raster and vector formats to that we can export images
//Raster image formats that support both - save and load and their default save options
Dictionary<string, ImageOptionsBase> rasterFormatsThatSupportExportAndImport = new Dictionary<string, ImageOptionsBase>()
{
{ "bmp", new BmpOptions()},
{ "gif", new GifOptions()},
{ "dicom", new DicomOptions()},
{ "jpg", new JpegOptions()},
{ "jpeg", new JpegOptions()},
{ "jpeg2000", new Jpeg2000Options() },
{ "j2k", new Jpeg2000Options { Codec = Aspose.Imaging.FileFormats.Jpeg2000.Jpeg2000Codec.J2K } },
{ "jp2", new Jpeg2000Options { Codec = Aspose.Imaging.FileFormats.Jpeg2000.Jpeg2000Codec.Jp2 }},
{ "png",new PngOptions(){ ColorType = PngColorType.TruecolorWithAlpha} },
{ "apng", new ApngOptions()},
{ "tiff", new Aspose.Imaging.ImageOptions.TiffOptions(Aspose.Imaging.FileFormats.Tiff.Enums.TiffExpectedFormat.Default)},
{ "tif", new Aspose.Imaging.ImageOptions.TiffOptions(Aspose.Imaging.FileFormats.Tiff.Enums.TiffExpectedFormat.Default)},
{ "tga", new TgaOptions()},
{ "webp", new WebPOptions()},
{ "ico", new IcoOptions()}
};
//Vector image formats that support both - save and load, their default save options
//and their rasterization options when exporting to another vector image
Dictionary<string, (ImageOptionsBase, VectorRasterizationOptions)> vectorFormatsThatSupportExportAndImport
= new Dictionary<string, (ImageOptionsBase, VectorRasterizationOptions)>()
{
{ "emf", (new EmfOptions(),new EmfRasterizationOptions()) },
{ "svg", (new SvgOptions(), new SvgRasterizationOptions())},
{ "wmf", (new WmfOptions(), new WmfRasterizationOptions())},
{ "emz", (new Aspose.Imaging.ImageOptions.EmfOptions(){ Compress = true }, new EmfRasterizationOptions())},
{ "wmz", (new Aspose.Imaging.ImageOptions.WmfOptions(){ Compress = true }, new WmfRasterizationOptions())},
{ "svgz", (new Aspose.Imaging.ImageOptions.SvgOptions(){ Compress = true }, new SvgRasterizationOptions())},
};
///Raster and vector formats from which we can load images
//Formats that can be only saved (supported only save to this formats)
Dictionary<string, ImageOptionsBase> formatsOnlyForExport = new Dictionary<string, ImageOptionsBase>()
{
{ "psd", new PsdOptions()},
{ "dxf", new DxfOptions(){ TextAsLines = true,ConvertTextBeziers = true} },
{ "pdf", new PdfOptions()},
{ "html", new Html5CanvasOptions()},
};
//Raster formats that can be only loaded
List<string> formatsOnlyForImport = new List<string>()
{
"djvu", "dng", "dib"
};
//Vector formats only for loading and their rasterization options when exporting to another vector format
Dictionary<string, VectorRasterizationOptions> vectorFormatsOnlyForImport = new Dictionary<string, VectorRasterizationOptions>()
{
{"eps", new EpsRasterizationOptions()},
{"cdr", new CdrRasterizationOptions() },
{"cmx", new CmxRasterizationOptions() },
{"otg", new OtgRasterizationOptions() },
{"odg", new OdgRasterizationOptions() }
};
//Get total set of formats to what we can export images
Dictionary<string, ImageOptionsBase> exportFormats = vectorFormatsThatSupportExportAndImport
.ToDictionary(s => s.Key, s => s.Value.Item1)
.Union(formatsOnlyForExport)
.Concat(rasterFormatsThatSupportExportAndImport)
.ToDictionary(s => s.Key, s => s.Value);
//Get total set of formats that can be loaded
Dictionary<string, VectorRasterizationOptions> importFormats = vectorFormatsOnlyForImport
.Union(formatsOnlyForImport.ToDictionary(s => s, s => new VectorRasterizationOptions()))
.Union(vectorFormatsThatSupportExportAndImport.ToDictionary(s => s.Key, s => s.Value.Item2))
.ToDictionary(s => s.Key, s => s.Value);
return (Import: importFormats, Export: exportFormats);
}
}
}
You can also refer to the official code: https://products.aspose.com/imaging/net/conversion/png-to-svg/

Related

Write Text file with tab-delimited in Asp.Net Core 2.2

Hi do you have any guides, work aid or step by step how to export to text with tab delimited. Im using Asp.Net Core 2.2 MVC EF. I want to export a list from my table.. I want to have a button where the user click in this DownloadFile Action will trigger.
public IActionResult DownloadFile()
{
var payments = new List<BdoPE>
{
new BdoPE
{
DocDateInDoc = "01/01/2019",
DocType = "DZ",
CompanyCode = "3000",
PosDateInDoc = "01/01/2019",
FiscalPeriod = "01",
CurrentKey = "PHP",
RefDocNum = "Over-The-Counter",
DocHeadT = "BDO",
PosKeyInNextLine = "40",
AccMatNextLine = "11231131",
AmountDocCur = "0000000010050",
ValDate = "01/01/2019",
AssignNum = "EEA",
ItemText = "1000136212 ",
PosKeyInNextLine2 = "15",
AccMatNextLine2 = "0115027FF",
AmountDocCur2 = "0000000010050",
BaseDateDueCal = "01/01/2019",
ItemText2 = "1000136212"
},
};
// I want this part to let the user select where they want to save the text file.
using (var writer = new StreamWriter("path\\to\\file.txt")) // not static location like this one.
using (var csv = new CsvWriter(writer))
{
csv.WriteHeader<BdoPE>();
csv.WriteRecord(payments);
}
// where should i put the delimiter part?
return;
}
You will need to setup the CsvWriter with a Configuration.
Thus, your code needs only a slight change:
[...]
var configuration = new CsvHelper.Configuration.Configuration();
configuration.Delimiter = '\t';
using (var csv = new CsvWriter(writer, configuration))
{
csv.WriteHeader<BdoPE>();
csv.WriteRecord(payments);
}
[...]
I use the code below to set the Delimiter using CsvHelper.
var config = new CsvConfiguration(CultureInfo.CurrentCulture)
{
Delimiter = "\t"
};

amazonS3client.SelectObjectContentAsync - downloading the large jsonline formate file - unwanted line break

I am trying to download a file content from the S3 bucket using the SelectObjectContentAsync method from AWSSDK for C#.
But there are some unwanted line break(\n) in mid of the raw data.
Data Example :
{"Id":1,"Name":"aaa"}, {"Id":2,"N
\name":"bbb"}
My Code :
var amazonS3Client = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, region);
SelectObjectContentRequest selectObjectContentRequest = new SelectObjectContentRequest()
{
Bucket = bucketName,
Key = key,
ExpressionType = ExpressionType.SQL,
Expression = query,
InputSerialization = new InputSerialization()
{
JSON = new JSONInput()
{
JsonType = JsonType.Lines
},
CompressionType = CompressionType.Gzip
},
OutputSerialization = new OutputSerialization()
{
JSON = new JSONOutput()
{
RecordDelimiter = ","
}
}
};
using (var content = amazonS3Client.SelectObjectContentAsync(selectObjectContentRequest).Result.Payload)
{
foreach (var item in content)
{
if (item is RecordsEvent recordsEvent)
{
using (var reader = new StreamReader(recordsEvent.Payload, Encoding.UTF8))
{
using (var file = new StreamWriter(path, true))
{
file.WriteLine(reader.ReadToEnd());
}
}
}
}
}

PDFBox doesn't embedd all Fonts

i'm using PDFBox in C# Project to create PDF/A and PDF/A3. Almost everything is working except that when I use PDFBox to convert a normal PDF-File to PDF/A not all Fonts are embedded. If I use Word to save as PDF/A the Font in Question is embedded. How do I embedd ArialMT too?
private PDDocumentCatalog makeDocPDFAcompliant(String producer, String creator)
{
PDDocumentCatalog cat = doc.getDocumentCatalog();
PDMetadata metadata = new PDMetadata(doc);
cat.setMetadata(metadata);
List<Dictionary<string, PDFont>> lstFonts = new List<Dictionary<string, PDFont>>();
List<PDFont> lstPDFonts= new List<PDFont>();
List pages = cat.getAllPages();
Iterator it = pages.iterator();
while (it.hasNext())
{
PDPage page = (PDPage)it.next();
var pageFont = page.getResources().getFonts();
lstFonts.Add(pageFont.ToDicitonary<string, PDFont>());
}
foreach (Dictionary<string, PDFont> d in lstFonts)
{
foreach (KeyValuePair<string, PDFont> entry in d)
{
PDFont font = entry.Value;
if (!lstPDFonts.Contains(font))
{
lstPDFonts.Add(font);
}
}
}
//PDType0Font font0 = PDType0Font.Load(doc,)
XMPMetadata xmp = new XMPMetadata();
XMPSchemaPDFAId pdfaid = new XMPSchemaPDFAId(xmp);
xmp.addSchema(pdfaid);
pdfaid.setConformance("A");
pdfaid.setPart(java.lang.Integer.valueOf(1));
pdfaid.setAbout("");
metadata.importXMPMetadata(xmp);
//System.IO.Stream asset = Zaumzeug.Properties.Resources.sRGB_Color_Space_Profile
System.IO.Stream stream = new System.IO.MemoryStream(Zaumzeug.Properties.Resources.sRGB_Color_Space_Profile);
InputStream colorProfile = new ikvm.io.InputStreamWrapper(stream);
PDOutputIntent oi = new PDOutputIntent(doc, colorProfile);
oi.setInfo("sRGB IEC61966-2.1");
oi.setOutputCondition("sRGB IEC61966-2.1");
oi.setOutputConditionIdentifier("sRGB IEC61966-2.1");
oi.setRegistryName("http://www.color.org");
cat.addOutputIntent(oi);
doc.save(#"D:\Examples .Net\Data\FontsNormalA.pdf");
return cat;
}

Pechkin converting webpage to pdf c# gives empty pdf.

I am exploring Pechkin to convert webpage to PDF. I have used article: http://ourcodeworld.com/articles/read/366/how-to-generate-a-pdf-from-html-using-wkhtmltopdf-with-c-in-winforms
Ref: How to use wkhtmltopdf.exe in ASP.net
When i try to convert using html string, it works !
byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert("<html><body><h1>Hello world!</h1></body></html>");
However when I follow "Generate PDF from a Website" section, I get empty pdf.
configuration.SetCreateExternalLinks(false)
.SetFallbackEncoding(Encoding.ASCII)
.SetLoadImages(true)
.SetPageUri("http://ourcodeworld.com");
Has anyone encountered same issue? Appreciate all help/suggestions.
Try to use
https://github.com/tuespetre/TuesPechkin
var document = new HtmlToPdfDocument
{
GlobalSettings =
{
ProduceOutline = true,
DocumentTitle = "Pretty Websites",
PaperSize = PaperKind.A4, // Implicit conversion to PechkinPaperSize
Margins =
{
All = 1.375,
Unit = Unit.Centimeters
}
},
Objects = {
new ObjectSettings { HtmlText = "<h1>Pretty Websites</h1><p>This might take a bit to convert!</p>" },
new ObjectSettings { PageUrl = "www.google.com" },
new ObjectSettings { PageUrl = "www.microsoft.com" },
new ObjectSettings { PageUrl = "www.github.com" }
}
};
var tempFolderDeployment = new TempFolderDeployment();
var win32EmbeddedDeployment = new Win32EmbeddedDeployment(tempFolderDeployment);
var remotingToolset = new RemotingToolset<PdfToolset>(win32EmbeddedDeployment);
var converter = ThreadSafeConverter(remotingToolset);
byte[] pdfBuf = converter.Convert(document);
// Very important - overwise cpu will grow !!!
remotingToolset.Unload();
Edit
If someone else use this- please read my post here- very important!
https://stackoverflow.com/a/62428122/4836581
If you get errors use this link that help me-
TuesPechkin unable to load DLL 'wkhtmltox.dll'
Found it thanks to-
https://stackoverflow.com/a/26993484/4836581

Filtering by .docx in ios document picker

What is the Uniform Type Identifer to provide to a UIDocumentMenuViewController to allow a user to select *.docx files?
The documentation in System-Declared Uniform Type Identifiers does not list a public UTType that allows filtering by .docx. An identifier exists for a standard *.doc file but not *.docx, is there instead an alternate UTType?
This is my current code:
var allowedDocumentTypes = new string[] {
UTType.RTF,
UTType.Text,
UTType.PDF,
UTType.UTF8PlainText,
UTType.RTFD,
UTType.UTF16ExternalPlainText,
UTType.UTF16PlainText,
UTType.UTF8PlainText,
UTType.FlatRTFD,
"com.microsoft.word.doc",
"com.microsoft.word.docx" // An attempt to include docx filtering.
};
var pickerMenu = new UIDocumentMenuViewController(allowedDocumentTypes, UIDocumentPickerMode.Open);
pickerMenu.DidPickDocumentPicker += (sender, args) =>
{
args.DocumentPicker.DidPickDocument += (sndr, pArgs) =>
{
var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource();
FileInfo fi = new FileInfo(pArgs.Url.Path);
var result = new SelectFileResult();
result.FilePath = fi.FullName;
result.FileName = fi.Name;
NSUrlRequest urlReq = NSUrlRequest.FromUrl(pArgs.Url);
NSUrlResponse response;
NSError error;;
var data = NSUrlConnection.SendSynchronousRequest(urlReq, out response, out error);
result.MimeType = response.MimeType;
Action onFileConsumeDone = () =>
{
pArgs.Url.StopAccessingSecurityScopedResource();
};
onFileSelected(result, onFileConsumeDone);
};
// Display the document picker
AppDelegate.TopViewController.PresentViewController(args.DocumentPicker, true, null);
};
pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover;
AppDelegate.TopViewController.PresentViewController(pickerMenu, true, null);
I had a shot in the dark and included the identifier com.microsoft.word.docx but it does not trigger filtering by docx.
My current solution is C# but objective-c and swift solutions accepted.
Try org.openxmlformats.wordprocessingml.document
Try
let supportedTypes: [UTType] = [UTType.content]

Categories

Resources