i cant enchant the result of the custom crafting recipe - plugins

Hi im trying to make this plugin where when ever someone crafts this custom recipe it will be a piece of paper that has the enchantment LUCK heres a example(without the enchantment):
ItemStack item = new ItemStack(Material.PAPER, 1);
ShapedRecipe recipe = new ShapedRecipe(item);
recipe.shape("^&^", "%#%", "^%^");
recipe.setIngredient('^', Material.NETHERITE_SCRAP);
recipe.setIngredient('&', Material.DIAMOND);
recipe.setIngredient('%', Material.GOLDEN_APPLE);
recipe.setIngredient('#', Material.NETHERITE_INGOT);
this.getServer().addRecipe(recipe);
this works fine but every time i try to enchant it, the entire crafting recipe doesn't work.
example:
ItemStack item = new ItemStack(Material.PAPER, 1);
ShapedRecipe recipe = new ShapedRecipe(item);
recipe.shape("^&^", "%#%", "^%^");
recipe.setIngredient('^', Material.NETHERITE_SCRAP);
recipe.setIngredient('&', Material.DIAMOND);
recipe.setIngredient('%', Material.GOLDEN_APPLE);
recipe.setIngredient('#', Material.NETHERITE_INGOT);
recipe.getResult().addEnchantment(Enchantment.LUCK, 1);
this.getServer().addRecipe(recipe);

Enchant before starting recipe :
ItemStack item = new ItemStack(Material.PAPER, 1);
ItemMeta meta = item.getItemMeta();
meta.addEnchant(Enchantement.LUCK, 1); // add enchant
item.setItemMeta(meta);
ShapedRecipe recipe = new ShapedRecipe(item); // now starting recipe creation
recipe.shape("^&^", "%#%", "^%^");
recipe.setIngredient('^', Material.NETHERITE_SCRAP);
recipe.setIngredient('&', Material.DIAMOND);
recipe.setIngredient('%', Material.GOLDEN_APPLE);
recipe.setIngredient('#', Material.NETHERITE_INGOT);
this.getServer().addRecipe(recipe);

Related

How to merge word documents with different headers using openxml?

I am trying to merge multiple documents into a single one by following examples as posted in this other post.
I am using AltChunk altChunk = new AltChunk(). When documents are merged, it does not seem to retain seperate hearders of each document. The merged document will contain the headers of the first document during the merging. If the first document being merged contains no hearders, then all the rest of the newly merged document will contain no headers, and vise versa.
My question is, how can I preserve different headers of the documents being merged?
Merge multiple word documents into one Open Xml
using System;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace WordMergeProject
{
public class Program
{
private static void Main(string[] args)
{
byte[] word1 = File.ReadAllBytes(#"..\..\word1.docx");
byte[] word2 = File.ReadAllBytes(#"..\..\word2.docx");
byte[] result = Merge(word1, word2);
File.WriteAllBytes(#"..\..\word3.docx", result);
}
private static byte[] Merge(byte[] dest, byte[] src)
{
string altChunkId = "AltChunkId" + DateTime.Now.Ticks.ToString();
var memoryStreamDest = new MemoryStream();
memoryStreamDest.Write(dest, 0, dest.Length);
memoryStreamDest.Seek(0, SeekOrigin.Begin);
var memoryStreamSrc = new MemoryStream(src);
using (WordprocessingDocument doc = WordprocessingDocument.Open(memoryStreamDest, true))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
AlternativeFormatImportPart altPart =
mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
altPart.FeedData(memoryStreamSrc);
var altChunk = new AltChunk();
altChunk.Id = altChunkId;
OpenXmlElement lastElem = mainPart.Document.Body.Elements<AltChunk>().LastOrDefault();
if(lastElem == null)
{
lastElem = mainPart.Document.Body.Elements<Paragraph>().Last();
}
//Page Brake einfügen
Paragraph pageBreakP = new Paragraph();
Run pageBreakR = new Run();
Break pageBreakBr = new Break() { Type = BreakValues.Page };
pageBreakP.Append(pageBreakR);
pageBreakR.Append(pageBreakBr);
return memoryStreamDest.ToArray();
}
}
}
I encountered this question a few years ago and spent quite some time on it; I eventually wrote a blog article that links to a sample file. Achieving integrating files with headers and footers using Alt-Chunk is not straight-forward. I'll try to cover the essentials, here. Depending on what kinds of content the headers and footers contain (and assuming Microsoft has not addressed any of the problems I originally ran into) it may not be possible to rely soley on AltChunk.
(Note also that there may be Tools/APIs that can handle this - I don't know and asking that on this site would be off-topic.)
Background
Before attacking the problem, it helps to understand how Word handles different headers and footers. To get a feel for it, start Word...
Section Breaks / Unlinking headers/footers
Type some text on the page and insert a header
Move the focus to the end of the page and go to the Page Layout tab in the Ribbon
Page Setup/Breaks/Next Page section break
Go into the Header area for this page and note the information in the blue "tags": you'll see a section identifier on the left and "Same as previous" on the right. "Same as Previous" is the default, to create a different Header click the "Link to Previous" button in the Header
So, the rule is:
a section break is required, with unlinked headers (and/or footers),
in order to have different header/footer content within a document.
Master/Sub-documents
Word has an (in)famous functionality called "Master Document" that enables linking outside ("sub") documents into a "master" document. Doing so automatically adds the necessary section breaks and unlinks the headers/footers so that the originals are retained.
Go to Word's Outline view
Click "Show Document"
Use "Insert" to insert other files
Notice that two section breaks are inserted, one of the type "Next page" and the other "Continuous". The first is inserted in the file coming in; the second in the "master" file.
Two section breaks are necessary when inserting a file because the last paragraph mark (which contains the section break for the end of the document) is not carried over to the target document. The section break in the target document carries the information to unlink the in-coming header from those already in the target document.
When the master is saved, closed and re-opened the sub documents are in a "collapsed" state (file names as hyperlinks instead of the content). They can be expanded by going back to the Outline view and clicking the "Expand" button. To fully incorporate a sub-document into the document click on the icon at the top left next to a sub-document then clicking "Unlink".
Merging Word Open XML files
This, then, is the type of environment the Open XML SDK needs to create when merging files whose headers and footers need to be retained. Theoretically, either approach should work. Practically, I had problems with using only section breaks; I've never tested using the Master Document feature in Word Open XML.
Inserting section breaks
Here's the basic code for inserting a section break and unlinking headers before bringing in a file using AltChunk. Looking at my old posts and articles, as long as there's no complex page numbering involved, it works:
private void btnMergeWordDocs_Click(object sender, EventArgs e)
{
string sourceFolder = #"C:\Test\MergeDocs\";
string targetFolder = #"C:\Test\";
string altChunkIdBase = "acID";
int altChunkCounter = 1;
string altChunkId = altChunkIdBase + altChunkCounter.ToString();
MainDocumentPart wdDocTargetMainPart = null;
Document docTarget = null;
AlternativeFormatImportPartType afType;
AlternativeFormatImportPart chunk = null;
AltChunk ac = null;
using (WordprocessingDocument wdPkgTarget = WordprocessingDocument.Create(targetFolder + "mergedDoc.docx", DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
//Will create document in 2007 Compatibility Mode.
//In order to make it 2010 a Settings part must be created and a CompatMode element for the Office version set.
wdDocTargetMainPart = wdPkgTarget.MainDocumentPart;
if (wdDocTargetMainPart == null)
{
wdDocTargetMainPart = wdPkgTarget.AddMainDocumentPart();
Document wdDoc = new Document(
new Body(
new Paragraph(
new Run(new Text() { Text = "First Para" })),
new Paragraph(new Run(new Text() { Text = "Second para" })),
new SectionProperties(
new SectionType() { Val = SectionMarkValues.NextPage },
new PageSize() { Code = 9 },
new PageMargin() { Gutter = 0, Bottom = 1134, Top = 1134, Left = 1318, Right = 1318, Footer = 709, Header = 709 },
new Columns() { Space = "708" },
new TitlePage())));
wdDocTargetMainPart.Document = wdDoc;
}
docTarget = wdDocTargetMainPart.Document;
SectionProperties secPropLast = docTarget.Body.Descendants<SectionProperties>().Last();
SectionProperties secPropNew = (SectionProperties)secPropLast.CloneNode(true);
//A section break must be in a ParagraphProperty
Paragraph lastParaTarget = (Paragraph)docTarget.Body.Descendants<Paragraph>().Last();
ParagraphProperties paraPropTarget = lastParaTarget.ParagraphProperties;
if (paraPropTarget == null)
{
paraPropTarget = new ParagraphProperties();
}
paraPropTarget.Append(secPropNew);
Run paraRun = lastParaTarget.Descendants<Run>().FirstOrDefault();
//lastParaTarget.InsertBefore(paraPropTarget, paraRun);
lastParaTarget.InsertAt(paraPropTarget, 0);
//Process the individual files in the source folder.
//Note that this process will permanently change the files by adding a section break.
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sourceFolder);
IEnumerable<System.IO.FileInfo> docFiles = di.EnumerateFiles();
foreach (System.IO.FileInfo fi in docFiles)
{
using (WordprocessingDocument pkgSourceDoc = WordprocessingDocument.Open(fi.FullName, true))
{
IEnumerable<HeaderPart> partsHeader = pkgSourceDoc.MainDocumentPart.GetPartsOfType<HeaderPart>();
IEnumerable<FooterPart> partsFooter = pkgSourceDoc.MainDocumentPart.GetPartsOfType<FooterPart>();
//If the source document has headers or footers we want to retain them.
//This requires inserting a section break at the end of the document.
if (partsHeader.Count() > 0 || partsFooter.Count() > 0)
{
Body sourceBody = pkgSourceDoc.MainDocumentPart.Document.Body;
SectionProperties docSectionBreak = sourceBody.Descendants<SectionProperties>().Last();
//Make a copy of the document section break as this won't be imported into the target document.
//It needs to be appended to the last paragraph of the document
SectionProperties copySectionBreak = (SectionProperties)docSectionBreak.CloneNode(true);
Paragraph lastpara = sourceBody.Descendants<Paragraph>().Last();
ParagraphProperties paraProps = lastpara.ParagraphProperties;
if (paraProps == null)
{
paraProps = new ParagraphProperties();
lastpara.Append(paraProps);
}
paraProps.Append(copySectionBreak);
}
pkgSourceDoc.MainDocumentPart.Document.Save();
}
//Insert the source file into the target file using AltChunk
afType = AlternativeFormatImportPartType.WordprocessingML;
chunk = wdDocTargetMainPart.AddAlternativeFormatImportPart(afType, altChunkId);
System.IO.FileStream fsSourceDocument = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Open);
chunk.FeedData(fsSourceDocument);
//Create the chunk
ac = new AltChunk();
//Link it to the part
ac.Id = altChunkId;
docTarget.Body.InsertAfter(ac, docTarget.Body.Descendants<Paragraph>().Last());
docTarget.Save();
altChunkCounter += 1;
altChunkId = altChunkIdBase + altChunkCounter.ToString();
chunk = null;
ac = null;
}
}
}
If there's complex page numbering (quoted from my blog article):
Unfortunately, there’s a bug in the Word application when integrating
Word document “chunks” into the main document. The process has the
nasty habit of not retaining a number of SectionProperties, among them
the one that sets whether a section has a Different First Page
() and the one to restart Page Numbering () in a section. As long as your documents don’t need to
manage these kinds of headers and footers you can probably use the
“altChunk” approach.
But if you do need to handle complex headers and footers the only
method currently available to you is to copy in the each document in
its entirety, part-by-part. This is a non-trivial undertaking, as
there are numerous possible types of Parts that can be associated not
only with the main document body, but also with each header and footer
part.
...or try the Master/Sub Document approach.
Master/Sub Document
This approach will certainly maintain all information, it will open as a Master document, however, and the Word API (either the user or automation code) is required to "unlink" the sub-documents to turn it into a single, integrated document.
Opening a Master Document file in the Open XML SDK Productivity Tool shows that inserting sub documents into the master document is a fairly straight-forward procedure:
The underlying Word Open XML for the document with one sub-document:
<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:p>
<w:pPr>
<w:pStyle w:val="Heading1" />
</w:pPr>
<w:subDoc r:id="rId6" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
</w:p>
<w:sectPr>
<w:headerReference w:type="default" r:id="rId7" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
<w:type w:val="continuous" />
<w:pgSz w:w="11906" w:h="16838" />
<w:pgMar w:top="1417" w:right="1417" w:bottom="1134" w:left="1417" w:header="708" w:footer="708" w:gutter="0" />
<w:cols w:space="708" />
<w:docGrid w:linePitch="360" />
</w:sectPr>
</w:body>
and the code:
public class GeneratedClass
{
// Creates an Body instance and adds its children.
public Body GenerateBody()
{
Body body1 = new Body();
Paragraph paragraph1 = new Paragraph();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "Heading1" };
paragraphProperties1.Append(paragraphStyleId1);
SubDocumentReference subDocumentReference1 = new SubDocumentReference(){ Id = "rId6" };
paragraph1.Append(paragraphProperties1);
paragraph1.Append(subDocumentReference1);
SectionProperties sectionProperties1 = new SectionProperties();
HeaderReference headerReference1 = new HeaderReference(){ Type = HeaderFooterValues.Default, Id = "rId7" };
SectionType sectionType1 = new SectionType(){ Val = SectionMarkValues.Continuous };
PageSize pageSize1 = new PageSize(){ Width = (UInt32Value)11906U, Height = (UInt32Value)16838U };
PageMargin pageMargin1 = new PageMargin(){ Top = 1417, Right = (UInt32Value)1417U, Bottom = 1134, Left = (UInt32Value)1417U, Header = (UInt32Value)708U, Footer = (UInt32Value)708U, Gutter = (UInt32Value)0U };
Columns columns1 = new Columns(){ Space = "708" };
DocGrid docGrid1 = new DocGrid(){ LinePitch = 360 };
sectionProperties1.Append(headerReference1);
sectionProperties1.Append(sectionType1);
sectionProperties1.Append(pageSize1);
sectionProperties1.Append(pageMargin1);
sectionProperties1.Append(columns1);
sectionProperties1.Append(docGrid1);
body1.Append(paragraph1);
body1.Append(sectionProperties1);
return body1;
}
}

Repeated lines in PdfPTable at the end of the page?

I'm using a PdfPTable (iText) to print a table that is populated with some list of values.
The problem is that, in the case where the PdfPTable takes more than one page to be displayed, its last line is printed at the end of the first page and ALSO at the beginning of the second one.
Please find an example below :
EDIT :
Please find the code below :
protected static PdfPTable addUserList(PdfWriter writer, Document document, List<MyObject> objects) throws Exception {
PdfPTable headerTable = new PdfPTable(4);
headerTable.setWidthPercentage(100);
headerTable.setWidths(new int[] { 4, 7, 5, 3 });
PdfPCell headerCell = PDFUtils.makeDefaultCell(1);
headerCell.setBorderColor(Color.WHITE);
headerCell.setBorder(PdfPCell.RIGHT);
headerCell.setBorderWidth(1f);
Phrase phrase = new Phrase("Column1", Style.OPIFICIO_12_BOLD_WHITE);
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
headerCell.setPhrase(phrase);
headerTable.addCell(headerCell);
phrase = new Phrase("Column2", Style.OPIFICIO_12_BOLD_WHITE);
headerCell.setPhrase(phrase);
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
headerTable.addCell(headerCell);
phrase = new Phrase("Column3", Style.OPIFICIO_12_BOLD_WHITE);
headerCell.setPhrase(phrase);
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
headerTable.addCell(headerCell);
phrase = new Phrase("Column4", Style.OPIFICIO_12_BOLD_WHITE);
Chunk chunk = new Chunk("(1)", Style.OPIFICIO_6_BOLD_WHITE);
chunk.setTextRise(7f);
phrase.add(chunk);
chunk = new Chunk("(XX)", Style.OPIFICIO_8_BOLD_WHITE);
chunk.setTextRise(1f);
phrase.add(chunk);
headerCell.setPhrase(phrase);
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
headerCell.setBorder(PdfPCell.NO_BORDER);
headerTable.addCell(headerCell);
PdfPTable userTable = new PdfPTable(4);
userTable.setWidthPercentage(100);
userTable.setWidths(new int[] { 4, 7, 5, 3 });
PdfPCell cell = PDFUtils.makeDefaultCell(1);
cell.setBackgroundColor(null);
cell.setPaddingTop(2f);
cell.setPaddingLeft(6f);
cell.setPaddingRight(6f);
for (MyObject object : objects) {
if (object != null) {
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
if (object.getAttribute1() != null) {
phrase = new Phrase(object.getAttribute1(), Style.FUTURASTD_10_NORMAL_BLACK);
} else {
phrase = new Phrase("", Style.FUTURASTD_10_NORMAL_BLACK);
}
cell.setBorderWidth(1f);
cell.setBorderColor(Color.WHITE);
cell.setBorder(PdfPCell.RIGHT);
cell.setPhrase(phrase);
userTable.addCell(cell);
phrase = new Phrase(object.getAttribute2(), Style.FUTURASTD_10_NORMAL_BLACK);
cell.setBorderWidth(1f);
cell.setBorderColor(Color.WHITE);
cell.setBorder(PdfPCell.RIGHT);
cell.setPhrase(phrase);
userTable.addCell(cell);
phrase = new Phrase(object.getAttribute3(), Style.FUTURASTD_10_NORMAL_BLACK);
cell.setBorderWidth(1f);
cell.setBorderColor(Color.WHITE);
cell.setBorder(PdfPCell.RIGHT);
cell.setPhrase(phrase);
userTable.addCell(cell);
phrase = new Phrase(object.getAttribute4(), Style.FUTURASTD_10_NORMAL_BLACK);
cell.setBorder(PdfPCell.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.setPhrase(phrase);
userTable.addCell(cell);
}
}
PdfPTable mainTable = new PdfPTable(1);
mainTable.setWidthPercentage(100);
mainTable.setSplitLate(false);
mainTable.setHeaderRows(1);
PdfPCell cellH = new PdfPCell();
cellH.addElement(headerTable);
cellH.setBorder(Rectangle.NO_BORDER);
cellH.setCellEvent(new PDFUtils.CellBackgroundRedRecap());
mainTable.addCell(cellH);
if (userTable.getRows().size() > 0) {
PdfPCell cellUser = PDFUtils.makeDefaultCell(1);
cellUser.setPaddingTop(7f);
cellUser.setCellEvent(new PDFUtils.CellBackgroundRecap());
cellUser.setBorder(PdfCell.NO_BORDER);
cellUser.addElement(userTable);
mainTable.addCell(cellUser);
}
return mainTable;
}
The problem actually was solved years ago (as #Bruno pointed out in a comment).
The solution, therefore, is to replace the older iText version used by a more current one in which the problem is fixed.
Indeed, the OP was having an old version in the pom.xml of another module of his project that was conflicting with the one he was modifying. He has deleted it and now it works.
Updating from versions 2.x (including the unofficial 4.2.0) to 5.x requires at least updating import statements as itext was moved from com.lowagie to com.itextpdf. Further changes might be necessary to adapt to actual API changes, e.g. the signing API was overhauled during the 5.3.x versions; the basic API structure, though, remained fairly stable during the 5.x versions.
Furthermore, updating from anything below 7 to 7.x requires greater changes as the whole iText API has been re-designed to get rid of sub-optimal aspects of the earlier API design.

Jasper Reports: Exporting report to multiple files

I'm developing a jrxml template for generate job candidate's resume. The candidates are in my database.
I need to generate a Word file (.docx) for 1 record (by job candidate), as the image below:
How can I make Jasper generate one file for each record of my SQL query? And export these files to Word?
I saw there is a parameter called PAGE_INDEX exporter. But I did not find how to use it ...
Can someone help me please?
Note 1: My reports are not generated by JasperServer. I developed a Java program to generate them and send reports by email.
Note 2: The number of pages for each candidate may be different.
Updating status
I managed to generate one record per file. But I could only generate the file to the first record.
I need to generate other files for the remaining records.
I'm still with the another problem too: how to separate into separate files when the number of pages for each record (candidate entity) can change?
final JRDocxExporter exporter = new JRDocxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new java.io.File("/home/admin/resume candidate.docx")));
SimpleDocxReportConfiguration configuration = new SimpleDocxReportConfiguration();
configuration.setPageIndex(0);
exporter.setConfiguration(configuration);
exporter.exportReport();
PROBLEM SOLUTION
I solved the problem by inserting a variable in the footer of each page with the expression: $V{REPORT_COUNT}, which have record count that is in the Detail Band:
After that, the Java program do loop between the pages of JasperPrint object.
So, i locate that element that tells me what page belongs to candidate.
Based on this information and storing candidate index data and its pages (in a HashMap > mapCandPage), I can determine the page that starts and the page ends for each candidate. And that way I can export one document for each candidate record.
public static void main(String args[]) throws Exception {
File relJasperArqFile = new File("Candidate Resume Template.jasper");
Connection conn = ConnectionFactory.getNewConnectionSQLDRIVER();
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relJasperArqFile);
JasperPrint jasperPrint
= JasperFillManager.fillReport(jasperReport,
null,
conn);
final JRDocxExporter exporter = new JRDocxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
List<JRPrintPage> listPrintPage = jasperPrint.getPages();
int candIdx = 0;
int fileIdx = 0;
int lastCandIdx = 0;
HashMap<Integer, List<Integer>> mapCandPage = new HashMap<>();
for (int pageIdx = 0; pageIdx < listPrintPage.size(); pageIdx++) {
JRPrintPage page = listPrintPage.get(pageIdx);
candIdx = getCandIdx(page);
if (!mapCandPage.containsKey(candIdx)) {
mapCandPage.put(candIdx, (new ArrayList<>()));
}
mapCandPage.get(candIdx).add(pageIdx);
if (pageIdx > 0 && candIdx != lastCandIdx) {
fileIdx++;
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new File(String.format("Candidate Resume %d.docx", fileIdx))));
SimpleDocxReportConfiguration configuration = new SimpleDocxReportConfiguration();
configuration.setStartPageIndex(mapCandPage.get(lastCandIdx).get(0));
configuration.setEndPageIndex(mapCandPage.get(lastCandIdx).get(mapCandPage.get(lastCandIdx).size() - 1));
exporter.setConfiguration(configuration);
exporter.exportReport();
}
lastCandIdx = candIdx;
}
fileIdx++;
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new File(String.format("Candidate Resume %d.docx", fileIdx))));
SimpleDocxReportConfiguration configuration = new SimpleDocxReportConfiguration();
configuration.setStartPageIndex(mapCandPage.get(lastCandIdx).get(0));
configuration.setEndPageIndex(mapCandPage.get(lastCandIdx).get(mapCandPage.get(lastCandIdx).size() - 1));
exporter.setConfiguration(configuration);
exporter.exportReport();
}
public static Integer getCandIdx(JRPrintPage page) {
JRPrintElement lastRowNumber = page.getElements().get(page.getElements().size() - 1);
return Integer.parseInt(((JRTemplatePrintText) lastRowNumber).getFullText());
}
This is a test and my code is not optimized. If anyone has suggestions or a better idea, please post here. Thank you.

Openxml: Added ImagePart is not showing in Powerpoint / Missing RelationshipID

I'm trying to dynamically create a PowerPoint presentation. One slide has a bunch of placeholder images that need to be changed based on certain values.
My approach is to create a new ImagePart and link it to the according Blip. The image is downloaded and stored to the presentation just fine. The problem is, that there is no relationship created in slide.xml.rels file for the image, which leads to an warning about missing images and empty boxes on the slide.
Any ideas what I am doing wrong?
Thanks in advance for your help! Best wishes
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(SPContext.Current.Site.RootWeb.Url))
{
using (SPWeb oWeb = siteCollection.OpenWeb())
{
SPList pictureLibrary = oWeb.Lists[pictureLibraryName];
SPFile imgFile = pictureLibrary.RootFolder.Files[imgPath];
byte[] byteArray = imgFile.OpenBinary();
int pos = Convert.ToInt32(name.Replace("QQ", "").Replace("Image", ""));
foreach (DocumentFormat.OpenXml.Presentation.Picture pic in pictureList)
{
var oldimg = pic.BlipFill.Blip.Embed.ToString(); ImagePart ip = (ImagePart)slidePart.AddImagePart(ImagePartType.Png, oldimg+pos);
using (var writer = new BinaryWriter(ip.GetStream()))
{
writer.Write(byteArray);
}
string newId = slidePart.GetIdOfPart(ip);
setDebugMessage("new img id: " + newId);
pic.BlipFill.Blip.Embed = newId;
}
slidePart.Slide.Save();
}
}
});
So, for everyone who's experiencing a similar problem, I finally found the solution. Quite a stupid mistake. Instad of PresentationDocument document = PresentationDocument.Open(mstream, true); you have to use
using (PresentationDocument document = PresentationDocument.Open(mstream, true))
{
do your editing here
}
This answer brought me on the right way.

How to read the unit price of an Item with IPP DevKit

I've seen elsewhere how to set the UnitPrice on an Item, using the wiley and elusive Item1 field as Intuit.Ipp.Data.Qbd.Money. But how do I READ the unit price from the Item1 field? I can't cast it. The new operator doesn't work ("new ...Money(myItem.Item1)"). So how do I get the price?
I realize the DevKit will probably never be changed so this makes sense. But can we at least get some doc explaining all those strange "xxxItemxxx" fields?
ServiceContext context = new ServiceContext(oauthValidator, realmId, intuitServiceType);
DataServices commonService = new DataServices(context);
Intuit.Ipp.Data.Qbd.Item qbdItem = new Intuit.Ipp.Data.Qbd.Item();
Intuit.Ipp.Data.Qbd.Money unitPrice = new Intuit.Ipp.Data.Qbd.Money();
unitPrice.Amount = 22;
unitPrice.AmountSpecified = true;
qbdItem.Item1 = unitPrice;
IEnumerable<Intuit.Ipp.Data.Qbd.Item> qbdItemsResult = commonService.FindAll(qbdItem, 1, 10) as IEnumerable<Intuit.Ipp.Data.Qbd.Item>;
foreach (var itemResult in qbdItemsResult)
{
Intuit.Ipp.Data.Qbd.Money test1UnitPrice = itemResult.Item1 as Intuit.Ipp.Data.Qbd.Money;
}
You can use the above code for .Net.
Response XML of Item entity suggests that 'UntiPrice' is a top level tag.
I tried this usecase using java. PFB code.
QBItemService itemService = QBServiceFactory.getService(context,QBItemService.class);
items = itemService.findAll(context,1, 100);
for (QBItem item : items) {
System.out.println("Name - " + item.getName() + " UnitPrice - " + item.getUnitPrice().getAmount());
Can you please try the same in .Net and let me know if it works in the same way.
Intuit.Ipp.Data.Qbd.Money [ getAmount() ]
Thanks