Images not showing in excel using npoi - npoi

The below code which uses npoi to create excel documents displays images in open office calc but not in excel.
If i open the doc in calc and save the document and then open the document in excel i can then see the images in excel.
Here is the code.
public static byte[] CreateExcel(CampaignViewModel viewModel, string fileName)
{
byte[] output;
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(#"\Data\templates\NPOITemplate.xls"), FileMode.Open, FileAccess.ReadWrite))
{
var templateWorkbook = new HSSFWorkbook(fs, true);
var sheet = templateWorkbook.GetSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = CsvHelper.GetMatrixAllLeftFields();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, templateWorkbook));
picture.Resize();
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID;
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
templateWorkbook.Write(ms);
output = ms.ToArray();
}
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}

i've resolved the above in a round about way. Turns out i didn't really need to use the template and could just create the xls from scratch. This add's a bit more meta data to the file which i suspect was the issue
public static byte[] CreateExcel2(CampaignViewModel viewModel, ICollection<DeliveryPoint> deliveryPoints, string fileName)
{
FileContentResult fileContentResult;
byte[] output;
var matrixCampaignLines = viewModel.MatrixCampaignLines;
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
var sheet = hssfworkbook.CreateSheet("Sheet1");
var patriarch = sheet.CreateDrawingPatriarch();
var leftFieldHeaders = (viewModel.Campaign.EnableNameOnCampaign) ? CsvHelper.GetMatrixAllLeftFields() : CsvHelper.GetMatrixAllLeftFieldsWithoutName();
var productHeaders = CsvHelper.GetMatrixProducts(viewModel.ProductCampaigns);
var totalCols = leftFieldHeaders.Count + productHeaders.Count;
var colWidth = 5000;
for (int i = 0; i < totalCols; i++)
{
sheet.SetColumnWidth(i, colWidth);
}
var imageRow = sheet.CreateRow(0);
imageRow.Height = 2000;
var imageCellCount = 0;
foreach (var header in leftFieldHeaders)
{
imageRow.CreateCell(imageCellCount).SetCellValue("");
imageCellCount++;
}
foreach (var product in viewModel.ProductCampaigns)
{
try
{
var anchor = new HSSFClientAnchor(0, 0, 0, 0, imageCellCount, 0, imageCellCount, 0);
anchor.AnchorType = 2;
var path = HttpContext.Current.Server.MapPath(product.Product.ImageThumbUrl);
var picture = patriarch.CreatePicture(anchor, LoadImage(#path, hssfworkbook));
picture.Resize();//Comment this line if your code crashes.
picture.LineStyle = HSSFPicture.LINESTYLE_SOLID; might not
}
catch (Exception)
{
}
imageCellCount++;
}
using (MemoryStream ms = new MemoryStream())
{
hssfworkbook.Write(ms);
output = ms.ToArray();
}
return output;
}
public static int LoadImage(string path, HSSFWorkbook wb)
{
try
{
var file = new FileStream(path, FileMode.Open, FileAccess.Read);
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
return wb.AddPicture(buffer, PictureType.JPEG);
}
catch (Exception)
{
return 0;
}
}

I got it right now.
I am using
try
{
ISheet sheet = templateWorkbook.GetSheet(sheetName);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
//create the anchor
HSSFClientAnchor anchor;
anchor = new HSSFClientAnchor(0, 0, 255, 255,
start.Col, start.Row, end.Col, end.Row);
anchor.AnchorType = 2;
patriarch.CreatePicture(anchor,
LoadImage(imagePath, templateWorkbook));
}
catch (IOException ioe)
{
}
and LoadImage() method which returns path from the server.
Use this one. It runs fine.

Related

iText7 how to add another pdf as background to exising pdf

I have 2 PDF files. under is single-page PDF file and must be a background for every page of original...
This is not working
public static byte[] overlay(byte[] original, byte[] under)
{
using (var resultStream = new MemoryStream())
{
var pdfWriter = new PdfWriter(resultStream);
var pdfReader = new PdfReader(new MemoryStream(original));
var pdfDoc = new PdfDocument(pdfReader, pdfWriter);
for (var p = 1; p <= pdfDoc.GetNumberOfPages(); p++)
{
var pdfUnder = new PdfDocument(new PdfReader(new MemoryStream(under)));
var pdfUnderPage = pdfUnder.GetFirstPage().CopyAsFormXObject(pdfDoc);
var page = pdfDoc.GetPage(p);
var canvas = new PdfCanvas(page.NewContentStreamBefore(),
page.GetResources(), pdfDoc);
canvas.AddXObjectAt(pdfUnderPage, 0, 0);
pdfUnder.Close();
}
pdfDoc.Close();
return resultStream.ToArray();
}
}

Add Image in Word Open SDK + dotnet core

I am trying to add an image to the word document using dotnet core and Open SDK library. Followed the exact same instruction as per the MSDN article. The code runs ok, but while trying to open document its says the document is corrupted.
Microsoft Doc
Used the OpenSDK Productivity tool and validated the document. Showing this error
Have confirmed that the Image Type are same. Not able to understand whats wrong.
private const string RefrenceKeyWord = "rId";
static void Main(string[] args)
{
InsertAPicture(document, fileName);
}
public static void InsertAPicture(string document, string fileName)
{
Int64Value imageWidth = 5731510L;
Int64Value imageHeight = 3820795L;
//using (var image = new Bitmap(fileName))
//{
// imageWidth = image.GetWidthInEMUs() / 10;
// imageHeight = image.GetHeightInEMUs() / 10;
//}
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
//## start of new Code ##
var maxId = mainPart.Parts
.Where(p => p.RelationshipId.StartsWith(RefrenceKeyWord))
.Select(p =>
Convert.ToInt32(p.RelationshipId.Replace(RefrenceKeyWord,
"")))
.Max();
mainPart.ChangeIdOfPart(imagePart, $"{RefrenceKeyWord}{maxId + 1}");
//## end of new Code ##
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), imageWidth, imageHeight);
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, Int64Value width, Int64Value height)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = width, Cy = height },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 2540L,
BottomEdge = 8255L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1",
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "Picture 1"
},
new PIC.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true, NoChangeArrowheads = true })),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}",
})
)
{
Embed = relationshipId,
//CompressionState =
//A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = width, Cy = height }),
new A.PresetGeometry(
new A.AdjustValueList()
)
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "https://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
SectionProperties sectPr = (SectionProperties)wordDoc.MainDocumentPart.Document.Body.ChildElements.Last();
// var p = wordDoc.MainDocumentPart.RootElement;
// var p1 = wordDoc.MainDocumentPart.Document.Body.FirstChild;
var p1 = new Paragaph(new Run(element));
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.InsertBefore(p1, sectPr);
}

Rgb 565 Pdf to Image

I am trying to convert a PDF page to an image, to create thumbnails. This is the code that I am using:
PdfRenderer pdfRenderer = new PdfRenderer(GetSeekableFileDescriptor(filePath));
var appDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
string directoryPath = System.IO.Path.Combine(appDirectory, "thumbnailsTemp", System.IO.Path.GetFileNameWithoutExtension(fileName));
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
int pageCount = pdfRenderer.PageCount;
for (int i = 0; i < pageCount; i++)
{
Page page = pdfRenderer.OpenPage(i);
Android.Graphics.Bitmap bmp = Android.Graphics.Bitmap.CreateBitmap(page.Width, page.Height, Android.Graphics.Bitmap.Config.Rgb565 or Argb8888);
page.Render(bmp, null, null, PdfRenderMode.ForDisplay);
try
{
using (FileStream output = new FileStream(System.IO.Path.Combine(directoryPath, fileName + "Thumbnails" + i + ".png"), FileMode.Create))
{
bmp.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, output);
}
page.Close();
}
catch (Exception ex)
{
//TODO -- GERER CETTE EXPEXPTION
throw new Exception();
}
}
return directoryPath;
}
I tried with ARGB 8888 and that was a success. But the rendering time was too slow for big PDF files. This is why I tried to improve it by changing the format to RGB 565. But my app is crashing with this Execption:
Unsuported pixel format
Any idea to fix this, or how to render a PDF to a bitmap faster? I was looking on google but didn't find a solution related to my code.
UPDATE
I did this but know, my app is crashing at this line of code :
await Task.Run(() =>
{
bytes = page.AsPNG(72);
});
My class :
public async Task<string> GetBitmaps(string filePath)
{
//TODO -- WORK ON THIS
PdfRenderer pdfRenderer = new PdfRenderer(GetSeekableFileDescriptor(filePath));
var appDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
string directoryPath = System.IO.Path.Combine(appDirectory, "thumbnailsTemp", System.IO.Path.GetFileNameWithoutExtension(fileName));
var stream = new MemoryStream();
using (Stream resourceStream = new FileStream(filePath, FileMode.Open))
{
resourceStream.CopyTo(stream);
}
for (int i = 0; i < pdfRenderer.PageCount; i++)
{
TallComponents.PDF.Rasterizer.Page page = new TallComponents.PDF.Rasterizer.Page(stream, i);
byte[] bytes = null;
await Task.Run(() =>
{
bytes = page.AsPNG(72);
});
using (FileStream output = new FileStream(System.IO.Path.Combine(directoryPath, fileName + "Thumbnails" + i + ".png"), FileMode.Create, FileAccess.Write))
{
output.Write(bytes, 0, bytes.Length);
}
}
return directoryPath;
}
you could draw a PDF page in app by converting a PDF page to a bitmap,here the PDF document itself is embedded as a resource.
var assembly = Assembly.GetExecutingAssembly();
var stream = new MemoryStream();
using (Stream resourceStream = assembly.GetManifestResourceStream("DrawPdf.Android.tiger.pdf"))
{
resourceStream.CopyTo(stream);
}
Page page = new Page(stream, 0);
// render PDF Page object to a Bitmap
byte[] bytes = null;
await Task.Run(() =>
{
bytes = page.AsPNG(72);
});
Bitmap bmp = global::Android.Graphics.BitmapFactory.DecodeByteArray(bytes, 0, bytes.Length);

i want to play music from webSite with the Mediaelement ," media.setSource()"

i get the stream from webSite ,then put it in isolatedStorage into IsolatedstorageStream ,
but it don't work ,no error no sound , what's wrong ????
HttpWebResponse reponse = request.EndGetResponse(result) as HttpWebResponse;
if (reponse.StatusCode == HttpStatusCode.OK)
{
Stream stream=reponse.GetResponseStream();
SaveMusic(stream, "music");
ReadMusic("music");
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
me.AutoPlay = true;
me.Volume = 100;
me.SetSource(songStream);
me.Play();
});
}
ok thanks keyboardP for your help ;here is my code
protected void SaveMusic(Stream stream,string name)
{
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!fileStorage.DirectoryExists("Source/Music"))
{
fileStorage.CreateDirectory("Source/Music");
}
using (IsolatedStorageFileStream fileStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("Source\\Music\\" + name + ".mp3", FileMode.Create))
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush();
}
}
protected void ReadMusic(string name)
{
using (IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
songStream = null;
songStream = new IsolatedStorageFileStream("Source\\Music\\" + name + ".mp3", FileMode.Open, fileStorage);
}
}
Assuming your saving and reading code is correct, your stream's position might be at the end. Try adding
songStream.Position = 0;
before SetSource(songStream);
Try using this to save the file:
using (var fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var buffer = new byte[1024];
using (var myIsStream = fileStorage.OpenFile("Source\\Music\\" + name + ".mp3", FileMode.CreateNew))
{
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, 1024)) > 0)
myIsStream.Write(buffer, 0, bytesRead);
}
}

Add table to powerpoint slide using Open XML

I got the code for the Table in the powerpoint using the code generator, but I am not able to add the table to an existing powerpoint document.
I tried adding another table to the intended slide and doing the following:
Table table = slidePart.Slide.Descendants<Table>().First();
table.RemoveAllChildren();
Table createdTable = CreateTable();
foreach (OpenXmlElement childElement in createdTable.ChildElements)
{
table.AppendChild(childElement.CloneNode(true));
}
But that didn't work.
I am out of ideas on this issue.
My original target is to add a table with dynamic number of columns and fixed number of row to my presentation.
I know its been very long since this question is posted, but just in case if some one needs a working code to create table in pptx.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Presentation;
using A = DocumentFormat.OpenXml.Drawing;
using System.IO;
namespace ANF.Slides.TestEngine
{
class Program
{
static int index = 1;
static void Main(string[] args)
{
Console.WriteLine("Preparing Presentation");
PopulateData();
// GeneratedClass cls=new GeneratedClass();
//cls.CreatePackage(#"E:\output.pptx");
Console.WriteLine("Completed Presentation");
Console.ReadLine();
}
private static void PopulateData()
{
var overflow = false;
const int pageBorder = 3000000;
var db = new AdventureWorksEntities();
var products = db.Products;//.Take(5);
const string outputFile = #"E:\openxml\output.pptx";
File.Copy(#"E:\OpenXml\Template.pptx", outputFile, true);
using (var myPres = PresentationDocument.Open(outputFile, true))
{
var presPart = myPres.PresentationPart;
var slideIdList = presPart.Presentation.SlideIdList;
var list = slideIdList.ChildElements
.Cast<SlideId>()
.Select(x => presPart.GetPartById(x.RelationshipId))
.Cast<SlidePart>();
var tableSlidePart = (SlidePart)list.Last();
var current = tableSlidePart;
long totalHeight = 0;
foreach (var product in products)
{
if (overflow)
{
var newTablePart = CloneSlidePart(presPart, tableSlidePart);
current = newTablePart;
overflow = false;
totalHeight = 0;
}
var tbl = current.Slide.Descendants<A.Table>().First();
var tr = new A.TableRow();
tr.Height = 200000;
tr.Append(CreateTextCell(product.Name));
tr.Append(CreateTextCell(product.ProductNumber));
tr.Append(CreateTextCell(product.Size));
tr.Append(CreateTextCell(String.Format("{0:00}", product.ListPrice)));
tr.Append(CreateTextCell(product.SellStartDate.ToShortDateString()));
tbl.Append(tr);
totalHeight += tr.Height;
if (totalHeight > pageBorder)
overflow = true;
}
}
}
static SlidePart CloneSlidePart(PresentationPart presentationPart, SlidePart slideTemplate)
{
//Create a new slide part in the presentation
SlidePart newSlidePart = presentationPart.AddNewPart<SlidePart>("newSlide" + index);
index++;
//Add the slide template content into the new slide
newSlidePart.FeedData(slideTemplate.GetStream(FileMode.Open));
//make sure the new slide references the proper slide layout
newSlidePart.AddPart(slideTemplate.SlideLayoutPart);
//Get the list of slide ids
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
//Figure out where to add the next slide (find max slide)
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
prevSlideId = slideId;
}
}
maxSlideId++;
//Add new slide at the end of the deck
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
//Make sure id and relid is set appropriately
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(newSlidePart);
return newSlidePart;
}
private static A.TableCell CreateTextCell(string text)
{
var textCol = new string[2];
if (!string.IsNullOrEmpty(text))
{
if (text.Length > 25)
{
textCol[0] = text.Substring(0, 25);
textCol[1] = text.Substring(26);
}
else
{
textCol[0] = text;
}
}
else
{
textCol[0] = string.Empty;
}
A.TableCell tableCell3 = new A.TableCell();
A.TextBody textBody3 = new A.TextBody();
A.BodyProperties bodyProperties3 = new A.BodyProperties();
A.ListStyle listStyle3 = new A.ListStyle();
textBody3.Append(bodyProperties3);
textBody3.Append(listStyle3);
var nonNull = textCol.Where(t => !string.IsNullOrEmpty(t)).ToList();
foreach (var textVal in nonNull)
{
//if (!string.IsNullOrEmpty(textVal))
//{
A.Paragraph paragraph3 = new A.Paragraph();
A.Run run2 = new A.Run();
A.RunProperties runProperties2 = new A.RunProperties() { Language = "en-US", Dirty = false, SmartTagClean = false };
A.Text text2 = new A.Text();
text2.Text = textVal;
run2.Append(runProperties2);
run2.Append(text2);
paragraph3.Append(run2);
textBody3.Append(paragraph3);
//}
}
A.TableCellProperties tableCellProperties3 = new A.TableCellProperties();
tableCell3.Append(textBody3);
tableCell3.Append(tableCellProperties3);
//var tc = new A.TableCell(
// new A.TextBody(
// new A.BodyProperties(),
// new A.Paragraph(
// new A.Run(
// new A.Text(text)))),
// new A.TableCellProperties());
//return tc;
return tableCell3;
}
}
}

Resources