Search in sources :

Example 11 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class XSSFHyperlink method generateRelationIfNeeded.

/**
     * Generates the relation if required
     */
protected void generateRelationIfNeeded(PackagePart sheetPart) {
    if (_externalRel == null && needsRelationToo()) {
        // Generate the relation
        PackageRelationship rel = sheetPart.addExternalRelationship(_location, XSSFRelation.SHEET_HYPERLINKS.getRelation());
        // Update the r:id
        _ctHyperlink.setId(rel.getId());
    }
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship)

Example 12 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class XWPFDocument method getAllEmbedds.

/**
     * Get the document's embedded files.
     */
@Override
public List<PackagePart> getAllEmbedds() throws OpenXML4JException {
    List<PackagePart> embedds = new LinkedList<PackagePart>();
    // Get the embeddings for the workbook
    PackagePart part = getPackagePart();
    for (PackageRelationship rel : getPackagePart().getRelationshipsByType(OLE_OBJECT_REL_TYPE)) {
        embedds.add(part.getRelatedPart(rel));
    }
    for (PackageRelationship rel : getPackagePart().getRelationshipsByType(PACK_OBJECT_REL_TYPE)) {
        embedds.add(part.getRelatedPart(rel));
    }
    return embedds;
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) LinkedList(java.util.LinkedList)

Example 13 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class TestXSSFHyperlink method testCreate.

@Test
public void testCreate() throws Exception {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet();
    XSSFRow row = sheet.createRow(0);
    XSSFCreationHelper createHelper = workbook.getCreationHelper();
    String[] urls = { "http://apache.org", "www.apache.org", "/temp", "c:/temp", "http://apache.org/default.php?s=isTramsformed&submit=Search&la=*&li=*" };
    for (int i = 0; i < urls.length; i++) {
        String s = urls[i];
        XSSFHyperlink link = createHelper.createHyperlink(HyperlinkType.URL);
        link.setAddress(s);
        XSSFCell cell = row.createCell(i);
        cell.setHyperlink(link);
    }
    workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook);
    sheet = workbook.getSheetAt(0);
    PackageRelationshipCollection rels = sheet.getPackagePart().getRelationships();
    assertEquals(urls.length, rels.size());
    for (int i = 0; i < rels.size(); i++) {
        PackageRelationship rel = rels.getRelationship(i);
        // there should be a relationship for each URL
        assertEquals(urls[i], rel.getTargetURI().toString());
    }
    // Bugzilla 53041: Hyperlink relations are duplicated when saving XSSF file
    workbook = XSSFTestDataSamples.writeOutAndReadBack(workbook);
    sheet = workbook.getSheetAt(0);
    rels = sheet.getPackagePart().getRelationships();
    assertEquals(urls.length, rels.size());
    for (int i = 0; i < rels.size(); i++) {
        PackageRelationship rel = rels.getRelationship(i);
        // there should be a relationship for each URL
        assertEquals(urls[i], rel.getTargetURI().toString());
    }
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) PackageRelationshipCollection(org.apache.poi.openxml4j.opc.PackageRelationshipCollection) Test(org.junit.Test)

Example 14 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class TestXWPFPictureData method testNew.

public void testNew() throws InvalidFormatException, IOException {
    XWPFDocument doc = XWPFTestDataSamples.openSampleDocument("EmptyDocumentWithHeaderFooter.docx");
    byte[] jpegData = XWPFTestDataSamples.getImage("nature1.jpg");
    assertNotNull(jpegData);
    byte[] gifData = XWPFTestDataSamples.getImage("nature1.gif");
    assertNotNull(gifData);
    byte[] pngData = XWPFTestDataSamples.getImage("nature1.png");
    assertNotNull(pngData);
    List<XWPFPictureData> pictures = doc.getAllPictures();
    assertEquals(0, pictures.size());
    // Document shouldn't have any image relationships
    assertEquals(13, doc.getPackagePart().getRelationships().size());
    for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
        if (rel.getRelationshipType().equals(XSSFRelation.IMAGE_JPEG.getRelation())) {
            fail("Shouldn't have JPEG yet");
        }
    }
    // Add the image
    String relationId = doc.addPictureData(jpegData, XWPFDocument.PICTURE_TYPE_JPEG);
    assertEquals(1, pictures.size());
    XWPFPictureData jpgPicData = (XWPFPictureData) doc.getRelationById(relationId);
    assertEquals("jpeg", jpgPicData.suggestFileExtension());
    assertArrayEquals(jpegData, jpgPicData.getData());
    // Ensure it now has one
    assertEquals(14, doc.getPackagePart().getRelationships().size());
    PackageRelationship jpegRel = null;
    for (PackageRelationship rel : doc.getPackagePart().getRelationships()) {
        if (rel.getRelationshipType().equals(XWPFRelation.IMAGE_JPEG.getRelation())) {
            if (jpegRel != null)
                fail("Found 2 jpegs!");
            jpegRel = rel;
        }
    }
    assertNotNull("JPEG Relationship not found", jpegRel);
    // Check the details
    assertNotNull(jpegRel);
    assertEquals(XWPFRelation.IMAGE_JPEG.getRelation(), jpegRel.getRelationshipType());
    assertEquals("/word/document.xml", jpegRel.getSource().getPartName().toString());
    assertEquals("/word/media/image1.jpeg", jpegRel.getTargetURI().getPath());
    XWPFPictureData pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
    assertArrayEquals(jpegData, pictureDataByID.getData());
    // Save an re-load, check it appears
    doc = XWPFTestDataSamples.writeOutAndReadBack(doc);
    assertEquals(1, doc.getAllPictures().size());
    assertEquals(1, doc.getAllPackagePictures().size());
    // verify the picture that we read back in
    pictureDataByID = doc.getPictureDataByID(jpegRel.getId());
    assertArrayEquals(jpegData, pictureDataByID.getData());
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship)

Example 15 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class XSSFWorkbook method cloneSheet.

/**
     * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
     *  The cloned sheet is a deep copy of the original but with a new given
     *  name.
     *
     * @param sheetNum The index of the sheet to clone
     * @param newName The name to set for the newly created sheet
     * @return XSSFSheet representing the cloned sheet.
     * @throws IllegalArgumentException if the sheet index or the sheet
     *         name is invalid
     * @throws POIXMLException if there were errors when cloning
     */
public XSSFSheet cloneSheet(int sheetNum, String newName) {
    validateSheetIndex(sheetNum);
    XSSFSheet srcSheet = sheets.get(sheetNum);
    if (newName == null) {
        String srcName = srcSheet.getSheetName();
        newName = getUniqueSheetName(srcName);
    } else {
        validateSheetName(newName);
    }
    XSSFSheet clonedSheet = createSheet(newName);
    // copy sheet's relations
    List<RelationPart> rels = srcSheet.getRelationParts();
    // if the sheet being cloned has a drawing then rememebr it and re-create it too
    XSSFDrawing dg = null;
    for (RelationPart rp : rels) {
        POIXMLDocumentPart r = rp.getDocumentPart();
        // do not copy the drawing relationship, it will be re-created
        if (r instanceof XSSFDrawing) {
            dg = (XSSFDrawing) r;
            continue;
        }
        addRelation(rp, clonedSheet);
    }
    try {
        for (PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) {
            if (pr.getTargetMode() == TargetMode.EXTERNAL) {
                clonedSheet.getPackagePart().addExternalRelationship(pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId());
            }
        }
    } catch (InvalidFormatException e) {
        throw new POIXMLException("Failed to clone sheet", e);
    }
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        srcSheet.write(out);
        clonedSheet.read(new ByteArrayInputStream(out.toByteArray()));
    } catch (IOException e) {
        throw new POIXMLException("Failed to clone sheet", e);
    }
    CTWorksheet ct = clonedSheet.getCTWorksheet();
    if (ct.isSetLegacyDrawing()) {
        logger.log(POILogger.WARN, "Cloning sheets with comments is not yet supported.");
        ct.unsetLegacyDrawing();
    }
    if (ct.isSetPageSetup()) {
        logger.log(POILogger.WARN, "Cloning sheets with page setup is not yet supported.");
        ct.unsetPageSetup();
    }
    clonedSheet.setSelected(false);
    // clone the sheet drawing alongs with its relationships
    if (dg != null) {
        if (ct.isSetDrawing()) {
            // unset the existing reference to the drawing,
            // so that subsequent call of clonedSheet.createDrawingPatriarch() will create a new one
            ct.unsetDrawing();
        }
        XSSFDrawing clonedDg = clonedSheet.createDrawingPatriarch();
        // copy drawing contents
        clonedDg.getCTDrawing().set(dg.getCTDrawing());
        clonedDg = clonedSheet.createDrawingPatriarch();
        // Clone drawing relations
        List<RelationPart> srcRels = srcSheet.createDrawingPatriarch().getRelationParts();
        for (RelationPart rp : srcRels) {
            addRelation(rp, clonedDg);
        }
    }
    return clonedSheet;
}
Also used : POIXMLDocumentPart(org.apache.poi.POIXMLDocumentPart) CTWorksheet(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet) POIXMLException(org.apache.poi.POIXMLException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) ByteArrayInputStream(java.io.ByteArrayInputStream)

Aggregations

PackageRelationship (org.apache.poi.openxml4j.opc.PackageRelationship)50 PackagePart (org.apache.poi.openxml4j.opc.PackagePart)28 InvalidFormatException (org.apache.poi.openxml4j.exceptions.InvalidFormatException)21 PackageRelationshipCollection (org.apache.poi.openxml4j.opc.PackageRelationshipCollection)15 PackagePartName (org.apache.poi.openxml4j.opc.PackagePartName)13 IOException (java.io.IOException)11 POIXMLException (org.apache.poi.POIXMLException)8 OPCPackage (org.apache.poi.openxml4j.opc.OPCPackage)5 TikaException (org.apache.tika.exception.TikaException)5 ArrayList (java.util.ArrayList)4 XmlException (org.apache.xmlbeans.XmlException)4 Test (org.junit.Test)4 InputStream (java.io.InputStream)3 URI (java.net.URI)3 HashMap (java.util.HashMap)3 OpenXML4JException (org.apache.poi.openxml4j.exceptions.OpenXML4JException)3 SAXException (org.xml.sax.SAXException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2