How to create PPTX file using power-point-template using Apache POI - templates

I want to create power-point presentation using power-point-template(which may be already exists or may be generated by poi.) for creating power point template file which have a background image in the slides, I write the following code which creates template file which opens in open-office but giving error to opening in Microsoft-power-point.
The Code is
private static void generatePOTX() throws IOException, FileNotFoundException {
String imgPathStr = System.getProperty("user.dir") + "/src/resources/images/TestSameChnl_001_t.jpeg";
File imgFile = new File(imgPathStr);
File potxFile = new File(System.getProperty("user.dir") + "/src/resources/Examples/layout.potx");
FileOutputStream out = new FileOutputStream(potxFile);
HSLFSlideShow ppt = new HSLFSlideShow();
HSLFSlide slide = ppt.createSlide();
slide.setFollowMasterBackground(false);
HSLFFill fill = slide.getBackground().getFill();
HSLFPictureData pd = ppt.addPicture(imgFile, PictureData.PictureType.JPEG);
fill.setFillType(HSLFFill.FILL_PICTURE);
fill.setPictureData(pd);
ppt.write(out);
out.close();
}
After that I tried to create a PPT file using the generated POTX file but
But it's giving error. I am trying bellow code for this.
And the code is
private static void GeneratePPTXUsingPOTX() throws FileNotFoundException, IOException {
File imgFile = new File(System.getProperty("user.dir")+"/src/resources/images/TestSameChnl_001_t.jpeg");
File potx_File = new File(System.getProperty("user.dir") + "/src/resources/Examples/layout.potx" );
File pptx_File = new File(System.getProperty("user.dir") + "/src/resources/Examples/PPTWithTemplate.pptx" );
File movieFile = new File(System.getProperty("user.dir") + "/src/resources/movie/Dummy.mp4");
FileInputStream ins = new FileInputStream(potx_File);
FileOutputStream out = new FileOutputStream(pptx_File);
HSLFSlideShow ppt = new HSLFSlideShow(ins);
List<HSLFSlide> slideList = ppt.getSlides();
int movieIdx = ppt.addMovie(movieFile.getAbsolutePath(), MovieShape.MOVIE_MPEG);
HSLFPictureData pictureData = ppt.addPicture(imgFile, PictureData.PictureType.JPEG);
MovieShape shape = new MovieShape(movieIdx, pictureData);
shape.setAnchor(new java.awt.Rectangle(300,225,420,280));
slideList.get(0).addShape(shape);
shape.setAutoPlay(true);
ppt.write(out);
out.close();
}
And the exception which is coming is as fallows:
java.lang.NullPointerException
at org.apache.poi.hslf.usermodel.HSLFPictureShape.afterInsert(HSLFPictureShape.java:185)
at org.apache.poi.hslf.usermodel.HSLFSheet.addShape(HSLFSheet.java:189)

Related

How can get byte of pdf before download? - Grails

I can download pdf file from AWS, download is working fine but I need get byte before download.
String awsBucket = params.awsBucket
String awsKey = params.awsKey
String fileName = params.fileName
String pdfLink = params.pdfLink
File file = grailsApplication.mainContext.getResource('WSCredential.properties').file
FileInputStream fileInputStream = new FileInputStream(file)
AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(fileInputStream))
GetObjectRequest getObjectRequest = new GetObjectRequest(awsBucket, awsKey)
userReceipt = s3Client.getObject(getObjectRequest)
if (userReceipt)
{
response.setContentType("application/image/png")
response.setHeader("Content-disposition", "attachment;filename=\"${fileName}\"")
response.outputStream << userReceipt.getObjectContent()
}
If you mean the size of PDF, then you can use HeadObject.

Using FileStreamResult to display PDF in browser

I am trying to display a PDF file in a browser using the action below.
When this is executed the result is an entire screen that looks like the image attached. Rendered result
It looks like MediaTypeNames.Application.Pdf is being ignored.
The same result with Chrome or Firfox.
What I am missing?
[HttpGet]
public FileResult ViewFile()
{
Response.AppendHeader("Content-Disposition", "inline; filename=" + Server.UrlEncode("file.pdf") + ";");
var path = #"C:\temp\file.pdf";
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
return new FileStreamResult(stream, MediaTypeNames.Application.Pdf);
}
You can use below below code snippet to display a PDF document in browser.
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
fileStream.Position = 0;
return new FileStreamResult(fileStream, System.Net.Mime.MediaTypeNames.Application.Pdf);

Writing Jena Models to Tar.Gz archives

I am working with RDF models at the moment. Therefore I query data from a database, generate models using Apache Jena and work with them. Although, I don't want to have to query the models every time I use them, so I thought about storing them locally. The models are quite big, so I'd like to compress them using Apache Commons Compress. This works so far (try-catch-blocks omitted):
public static void write(Map<String, Model> models, String file){
logger.info("Writing models to file " + file);
TarArchiveOutputStream tarOutput = null;;
TarArchiveEntry entry = null;
tarOutput = new TarArchiveOutputStream(new GzipCompressorOutputStream(new FileOutputStream(new File(file))));
for(Map.Entry<String, Model> e : models.entrySet()) {
logger.info("Packing model " + e.getKey());
// Convert Model
ByteArrayOutputStream baos = new ByteArrayOutputStream();
RDFDataMgr.write(baos,e.getValue(), RDFFormat.RDFXML_PRETTY);
// Prepare Entry
entry = new TarArchiveEntry(e.getKey());
entry.setSize(baos.size());
tarOutput.putArchiveEntry(entry);
// write into file and close
tarOutput.write(baos.toByteArray());
tarOutput.closeArchiveEntry();
}
tarOutput.close();
}
But as I try the other direction, I get weird NullPointerExceptions. Is this a bug in the GZip-Implementation or is my understanding of Streams wrong?
public static Map<String, Model> read(String file){
logger.info("Reading models from file " + file);
Map<String, Model> models = new HashMap<>();
TarArchiveInputStream tarInput = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(file)));
for(TarArchiveEntry currentEntry = tarInput.getNextTarEntry();currentEntry != null; currentEntry= tarInput.getNextTarEntry()){
logger.info("Processing model " + currentEntry.getName());
// Read the current model
Model m = ModelFactory.createDefaultModel();
m.read(tarInput, null);
// And add it to the output
models.put(currentEntry.getName(),m);
tarInput.close();
}
return models;
}
This is the stack trace:
Exception in thread "main" java.lang.NullPointerException
at org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream.read(GzipCompressorInputStream.java:271)
at java.io.InputStream.skip(InputStream.java:224)
at org.apache.commons.compress.utils.IOUtils.skip(IOUtils.java:106)
at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.skipRecordPadding(TarArchiveInputStream.java:345)
at org.apache.commons.compress.archivers.tar.TarArchiveInputStream.getNextTarEntry(TarArchiveInputStream.java:272)
at de.mem89.masterthesis.rdfHydra.StorageHelper.read(StorageHelper.java:88)
at de.mem89.masterthesis.rdfHydra.StorageHelper.main(StorageHelper.java:124)

How to set HtmlSaveOptions to save html and resources to stream using Aspose PDF

I am trying to use Aspose.PDF to load PDF from databases, convert it to HTML and render them to our web page.I want to know if we can save both the document and the resource to stream since current example in the document of Aspose.PDF saves css and images to a local path. I have tried this but the is and error that Aspose.Pdf.SaveFormat.Html is not supported.
Aspose.Pdf.Document PDFDocument = new Aspose.Pdf.Document(PDFStream);
MemoryStream HTMLStreamFromPDF = new MemoryStream();
PDFDocument.Save(HTMLStreamFromPDF, Aspose.Pdf.SaveFormat.Html);
If it can be done, how to write the parameters of CustomResourceSavingStrategy, CustomCssSavingStrategy, and CustomStrategyOfCssUrlCreation of HtmlSaveOptions. I am sorry that I am not quite familiar with delegate in C#
Thanks!
Finally found a way to save all files to stream.
MemoryStream HTMLStreamFromPDF = new MemoryStream();
List<MemoryStream> ResourseStreamList = new List<MemoryStream>();
List<string> ResourceNameList = new List<string>();
MemoryStream CSSStream = new MemoryStream();
Aspose.Pdf.HtmlSaveOptions saveOptions = new Aspose.Pdf.HtmlSaveOptions();
CustomResourcesProcessingBind customResourcesProcessingBind = new CustomResourcesProcessingBind((_1) => CustomResourcesProcessing(ResourseStreamList,ResourceNameList, RequestURL, _1));
saveOptions.CustomResourceSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.ResourceSavingStrategy(customResourcesProcessingBind);
CssUrlCreationCustomStrategyBind cssUrlCreationCustomStrategyBind = new CssUrlCreationCustomStrategyBind((_1) => CssUrlCreationCustomStrategy(RequestURL, _1));
saveOptions.CustomStrategyOfCssUrlCreation = new Aspose.Pdf.HtmlSaveOptions.CssUrlMakingStrategy(cssUrlCreationCustomStrategyBind);
CustomCssSavingProcessingBind customCssSavingProcessingBind = new CustomCssSavingProcessingBind((_1) => CustomCssSavingProcessing(CSSStream, _1));
saveOptions.CustomCssSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.CssSavingStrategy(customCssSavingProcessingBind);
saveOptions.HtmlMarkupGenerationMode = Aspose.Pdf.HtmlSaveOptions.HtmlMarkupGenerationModes.WriteOnlyBodyContent;
PDFDocument.Save(HTMLStreamFromPDF, saveOptions);
private delegate string CustomResourcesProcessingBind(Aspose.Pdf.SaveOptions.ResourceSavingInfo resourceSavingInfo);
private static string CustomResourcesProcessing(List<MemoryStream> ResourseStreamList, List<string> ResourceNameList, string RequestURL, Aspose.Pdf.SaveOptions.ResourceSavingInfo resourceSavingInfo)
{
MemoryStream newResource = new MemoryStream();
resourceSavingInfo.ContentStream.CopyTo(newResource);
ResourceNameList.Add(resourceSavingInfo.SupposedFileName);
ResourseStreamList.Add(newResource);
string urlThatWillBeUsedInHtml = RequestURL +"/"+ Path.GetFileName(resourceSavingInfo.SupposedFileName);
return urlThatWillBeUsedInHtml;
}
private delegate string CssUrlCreationCustomStrategyBind(Aspose.Pdf.HtmlSaveOptions.CssUrlRequestInfo requestInfo);
private static string CssUrlCreationCustomStrategy(string RequestURL,Aspose.Pdf.HtmlSaveOptions.CssUrlRequestInfo requestInfo)
{
return RequestURL + "/css_style.css";
}
private delegate void CustomCssSavingProcessingBind(Aspose.Pdf.HtmlSaveOptions.CssSavingInfo resourceInfo);
private static void CustomCssSavingProcessing(MemoryStream CSSStream, Aspose.Pdf.HtmlSaveOptions.CssSavingInfo resourceInfo)
{
resourceInfo.ContentStream.CopyTo(CSSStream);
}
Check the following sample code regarding how to use parameters CustomResourceSavingStrategy, CustomCssSavingStrategy and CustomStrategyOfCssUrlCreation of HtmlSaveOptions when converting from PDF to HTML.
static string _folderForReferencedResources;
static void Main(string[] args)
{
Document pdfDocument = new Document(#"F:\ExternalTestsData\input.pdf");
string outHtmlFile = #"F:\ExternalTestsData\output.html";
_folderForReferencedResources = #"F:\ExternalTestsData\resources\";
//-----------------------------------------------------
// 2)clean results if they already present
//-----------------------------------------------------
if (Directory.Exists(_folderForReferencedResources))
{
Directory.Delete(_folderForReferencedResources, true);
}
File.Delete(outHtmlFile);
//-----------------------------------------------------
// create HtmlSaveOption with tested feature
//-----------------------------------------------------
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(Strategy_11_CUSTOM_SAVE_OF_FONTS_AND_IMAGES);
saveOptions.CustomCssSavingStrategy = new HtmlSaveOptions.CssSavingStrategy(Strategy_11_CSS_WriteCssToPredefinedFolder);
saveOptions.CustomStrategyOfCssUrlCreation = new HtmlSaveOptions.CssUrlMakingStrategy(Strategy_11_CSS_ReturnResultPathInPredefinedTestFolder);
using (Stream outStream = File.OpenWrite(outHtmlFile))
{
pdfDocument.Save(outStream, saveOptions);
}
}
private static void Strategy_11_CSS_WriteCssToPredefinedFolder(HtmlSaveOptions.CssSavingInfo resourceInfo)
{
if (!Directory.Exists(_folderForReferencedResources))
{
Directory.CreateDirectory(_folderForReferencedResources);
}
string path = _folderForReferencedResources + Path.GetFileName(resourceInfo.SupposedURL);
System.IO.BinaryReader reader = new BinaryReader(resourceInfo.ContentStream);
System.IO.File.WriteAllBytes(path, reader.ReadBytes((int)resourceInfo.ContentStream.Length));
}
private static string Strategy_11_CSS_ReturnResultPathInPredefinedTestFolder(HtmlSaveOptions.CssUrlRequestInfo requestInfo)
{
return "file:///" + _folderForReferencedResources.Replace(#"\", "/") + "css_style{0}.css";
}
private static string Strategy_11_CUSTOM_SAVE_OF_FONTS_AND_IMAGES(SaveOptions.ResourceSavingInfo resourceSavingInfo)
{
if (!Directory.Exists(_folderForReferencedResources))
{
Directory.CreateDirectory(_folderForReferencedResources);
}
string path = _folderForReferencedResources + Path.GetFileName(resourceSavingInfo.SupposedFileName);
// first path of this method is for saving of font
System.IO.BinaryReader contentReader = new BinaryReader(resourceSavingInfo.ContentStream);
System.IO.File.WriteAllBytes(path, contentReader.ReadBytes((int)resourceSavingInfo.ContentStream.Length));
string urlThatWillBeUsedInHtml = "file:///" + _folderForReferencedResources.Replace(#"\", "/") + Path.GetFileName(resourceSavingInfo.SupposedFileName);
return urlThatWillBeUsedInHtml;
}
The details are available here.
P.S. I am Social Media Developer at Aspose.

Reading HAR file from DistributedCache in mapreduce

I've written an oozie workflow which creates HAR archive and then runs MR-job which needs to read data from this archive.
1. Archive is created
2. When job runs, mapper does see archive in distributed cache.
3. ??? How Can I read this arhive? What's the API to read data from this archive line by line (my har is batch of multiple new line separated text files).
NB: It work perfectly when i work with usual files (not HAR archive) stored in DistirubtedCache. I got a problem while trying to read data from HAR.
Here is a code snippet:
InputStream inputStream;
String cachedDatafileName = System.getProperty(DIST_CACHE_FILE_NAME);
LOG.info(String.format("Looking for[%s]=[%s] in DistributedCache",DIST_CACHE_FILE_NAME, cachedDatafileName));
URI[] uris = DistributedCache.getCacheArchives(getContext().getConfiguration());
URI uriToCachedDatafile = null;
for(URI uri : uris){
if(uri.toString().endsWith(cachedDatafileName)){
uriToCachedDatafile = uri;
break;
}
}
if(uriToCachedDatafile == null){
throw new RuntimeConfigurationException(String.format("Looking for[%s]=[%s] in DistributedCache failed. There is no such file",
DIST_CACHE_FILE_NAME, cachedDatafileName));
}
Path pathToFile = new Path(uriToCachedDatafile);
LOG.info(String.format("[%s] has been found. Uri is: [%s]. The path is:[%s]",cachedDatafileName, uriToCachedDatafile, pathToFile));
FileSystem fileSystem = pathToFile.getFileSystem(getContext().getConfiguration());
HarFileSystem harFileSystem = new HarFileSystem(fileSystem);
inputStream = harFileSystem.open(pathToFile); //NULL POINTER EXCEPTION IS HERE!
return inputStream;
protected InputStream getInputStreamToDistCacheFile() throws IOException{
InputStream inputStream;
String cachedDatafileName = System.getProperty(DIST_CACHE_FILE_NAME);
LOG.info(String.format("Looking for[%s]=[%s] in DistributedCache",DIST_CACHE_FILE_NAME, cachedDatafileName));
URI[] uris = DistributedCache.getCacheArchives(getContext().getConfiguration());
URI uriToCachedDatafile = null;
for(URI uri : uris){
if(uri.toString().endsWith(cachedDatafileName)){
uriToCachedDatafile = uri;
break;
}
}
if(uriToCachedDatafile == null){
throw new RuntimeConfigurationException(String.format("Looking for[%s]=[%s] in DistributedCache failed. There is no such file",
DIST_CACHE_FILE_NAME, cachedDatafileName));
}
//Path pathToFile = new Path(uriToCachedDatafile +"/stf/db_bts_stf.txt");
Path pathToFile = new Path("har:///"+"home/ssa/devel/megalabs/kyc-solution/kyc-mrjob/target/test-classes/GSMCellSubscriberHomeIntersectionJobDescriptionClusterMRTest/in/gsm_cell_location_stf.har" +"/stf/db_bts_stf.txt");
//Path pathToFile = new Path(("har://home/ssa/devel/megalabs/kyc-solution/kyc-mrjob/target/test-classes/GSMCellSubscriberHomeIntersectionJobDescriptionClusterMRTest/in/gsm_cell_location_stf.har"));
LOG.info(String.format("[%s] has been found. Uri is: [%s]. The path is:[%s]",cachedDatafileName, uriToCachedDatafile, pathToFile));
FileSystem harFileSystem = pathToFile.getFileSystem(context.getConfiguration());
FSDataInputStream fin = harFileSystem.open(pathToFile);
LOG.info("fin: " + fin);
// FileSystem fileSystem = pathToFile.getFileSystem(getContext().getConfiguration());
// HarFileSystem harFileSystem = new HarFileSystem(fileSystem);
// harFileSystem.exists(new Path("har://home/ssa/devel/mycompany/my-solution/my-mrjob/target/test-classes/HomeJobDescriptionClusterMRTest/in/locations.har"));
// LOG.info("harFileSystem.exists(pathToFile):"+ harFileSystem.exists(pathToFile));
// harFileSystem.initialize(uriToCachedDatafile, context.getConfiguration());
FileStatus[] statuses = harFileSystem.listStatus(new Path("har:///"+"har://home/ssa/devel/mycompany/my-solution/my-mrjob/target/test-classes/HomeJobDescriptionClusterMRTest/in/locations.har"));
for(FileStatus fileStatus : statuses){
LOG.info("fileStatus isDir"+fileStatus.isDirectory() +" len:" + fileStatus.getLen());
}
// String tmpPathToFile = "har:///"+pathToFile.toString(); //+"/stf/db_bts_stf.txt";
// Path tmpPath = new Path(tmpPathToFile);
// LOG.info("KILL ME PATH TO FILE IN ARCHIVE: " +tmpPath);
// inputStream = harFileSystem.open(tmpPath);
// return inputStream;
return fin;
}
As you can see, it's terrible. You have manually read index file stored inside archive and reconstruct paths using index file metadata. If you know the exact name of a file stored in archive (like in my example), you can construct paths manually.
It's not convinient.I did expect something like Zip->zipEntry, when you can iterate over entries of archive without knowing it's structure.