Coder Social home page Coder Social logo

help,add image to hwp about hwplib HOT 26 CLOSED

neolord0 avatar neolord0 commented on August 23, 2024
help,add image to hwp

from hwplib.

Comments (26)

neolord0 avatar neolord0 commented on August 23, 2024

firstParagraph.getText().addExtendCharForGSO();
=> HWP proesses a Shape as Character in paragraph. So, If Shape add into Paragraph, You must add extended characters to the position of the glyph in the paragraph. This code is it.

header.setInstanceId(0x5bb840e1);
=> The value "0x5bb840e1" is a default value for HWP. This has not been documented. I has read the file and found out.

My sample code has added an image using the rectangle control, but You used the picture control. I do not know exactly how to do this. Your code seems to be missing some setting. Send me your entire code. I will do some more research. My mail address is [email protected].

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

thank you,code has been send.

but i am be afraid email lose something so ,put code here

package kr.dogfoot.hwplib;

import kr.dogfoot.hwplib.object.HWPFile;
import kr.dogfoot.hwplib.object.bodytext.Section;
import kr.dogfoot.hwplib.object.bodytext.control.ControlTable;
import kr.dogfoot.hwplib.object.bodytext.control.ControlType;
import kr.dogfoot.hwplib.object.bodytext.control.ctrlheader.CtrlHeaderGso;
import kr.dogfoot.hwplib.object.bodytext.control.ctrlheader.gso.*;
import kr.dogfoot.hwplib.object.bodytext.control.gso.ControlPicture;
import kr.dogfoot.hwplib.object.bodytext.control.gso.GsoControlType;
import kr.dogfoot.hwplib.object.bodytext.control.gso.shapecomponent.ShapeComponentNormal;
import kr.dogfoot.hwplib.object.bodytext.control.gso.shapecomponent.lineinfo.*;
import kr.dogfoot.hwplib.object.bodytext.control.gso.shapecomponent.shadowinfo.ShadowInfo;
import kr.dogfoot.hwplib.object.bodytext.control.gso.shapecomponent.shadowinfo.ShadowType;
import kr.dogfoot.hwplib.object.bodytext.control.gso.shapecomponenteach.ShapeComponentPicture;
import kr.dogfoot.hwplib.object.bodytext.control.gso.shapecomponenteach.polygon.PositionXY;
import kr.dogfoot.hwplib.object.bodytext.control.table.DivideAtPageBoundary;
import kr.dogfoot.hwplib.object.bodytext.control.table.Row;
import kr.dogfoot.hwplib.object.bodytext.control.table.Table;
import kr.dogfoot.hwplib.object.bodytext.paragraph.Paragraph;
import kr.dogfoot.hwplib.object.docinfo.BinData;
import kr.dogfoot.hwplib.object.docinfo.bindata.BinDataCompress;
import kr.dogfoot.hwplib.object.docinfo.bindata.BinDataState;
import kr.dogfoot.hwplib.object.docinfo.bindata.BinDataType;
import kr.dogfoot.hwplib.object.docinfo.borderfill.fillinfo.PictureEffect;
import kr.dogfoot.hwplib.object.docinfo.borderfill.fillinfo.PictureInfo;
import kr.dogfoot.hwplib.object.etc.Color4Byte;
import kr.dogfoot.hwplib.reader.HWPReader;
import kr.dogfoot.hwplib.test.TestOwerTable;
import kr.dogfoot.hwplib.writer.HWPWriter;
import org.apache.poi.util.IOUtils;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class TestWriteImage {
    public static void main(String[] args) throws Exception {
        String filename = "sample_hwp\\test-blank.hwp";

        HWPFile hwpFile = HWPReader.fromFile(filename);
        if (hwpFile != null) {
            TestOwerTable tmt = new TestOwerTable();

            Section firstSection = hwpFile.getBodyText().getSectionList().get(0);
            Paragraph firstParagraph = firstSection.getParagraph(0);


            int streamIndex = hwpFile.getBinData().getEmbeddedBinaryDataList().size() + 1;
            String streamName = getStreamName(streamIndex, "jpg");
            byte[] fileBinary = loadFile(); //load image
            Rectangle shapePosition = new Rectangle(0, 3, 30, 30);
            hwpFile.getBinData().addNewEmbeddedBinaryData(streamName, fileBinary);
            int binDataID = addBinDataInDocInfo(hwpFile, streamIndex);
            firstParagraph.getText().addExtendCharForGSO();
            ControlPicture controlPicture = (ControlPicture) firstParagraph.addNewGsoControl(GsoControlType.Picture);

            CtrlHeaderGso header = controlPicture.getHeader();
            GsoHeaderProperty prop = header.getProperty();
            prop.setLikeWord(false);
            prop.setApplyLineSpace(false);
            prop.setVertRelTo(VertRelTo.Para);
            prop.setVertRelativeArrange(RelativeArrange.TopOrLeft);
            prop.setHorzRelTo(HorzRelTo.Para);
            prop.setHorzRelativeArrange(RelativeArrange.TopOrLeft);
            prop.setVertRelToParaLimit(true);
            prop.setAllowOverlap(true);
            prop.setWidthCriterion(WidthCriterion.Absolute);
            prop.setHeightCriterion(HeightCriterion.Absolute);
            prop.setProtectSize(false);
            prop.setTextFlowMethod(TextFlowMethod.TopAndBottom);
            prop.setTextHorzArrange(TextHorzArrange.BothSides);
            prop.setObjectNumberSort(ObjectNumberSort.Figure);

            header.setyOffset(fromMM(shapePosition.y));
            header.setxOffset(fromMM(shapePosition.x));
            header.setWidth(fromMM(shapePosition.width));
            header.setHeight(fromMM(shapePosition.height));
            header.setzOrder(0);
            header.setOutterMarginLeft(0);
            header.setOutterMarginRight(0);
            header.setOutterMarginTop(0);
            header.setOutterMarginBottom(0);
            header.setInstanceId(0x5bb840e1);
            header.setPreventPageDivide(false);
            header.setExplanation(null);
//
            ShapeComponentPicture scp = controlPicture.getShapeComponentPicture();

            Color4Byte borderColor = scp.getBorderColor();
            borderColor.setValue(0);


            LineInfoProperty borderProperty = scp.getBorderProperty();
            borderProperty.setLineEndShape(LineEndShape.Flat);
            borderProperty.setStartArrowShape(LineArrowShape.None);
            borderProperty.setStartArrowSize(LineArrowSize.MiddleMiddle);
            borderProperty.setEndArrowShape(LineArrowShape.None);
            borderProperty.setEndArrowSize(LineArrowSize.MiddleMiddle);
            borderProperty.setLineType(LineType.None);
            borderProperty.setFillStartArrow(true);
            borderProperty.setFillEndArrow(true);

            PositionXY leftTop = scp.getLeftTop();
            PositionXY leftBottom = scp.getLeftBottom();
            PositionXY rightBottom = scp.getRightBottom();
            PositionXY rightTop = scp.getRightTop();

            leftTop.setX(0);
            leftTop.setY(fromMM(shapePosition.height));
            rightTop.setX(fromMM(shapePosition.width));
            rightTop.setY(fromMM(shapePosition.height));
            leftBottom.setX(0);
            leftBottom.setY(0);
            rightBottom.setX(fromMM(shapePosition.width));
            rightBottom.setY(0);


            PictureInfo pictureInfo = scp.getPictureInfo();
            pictureInfo.setBinItemID(binDataID);
//            pictureInfo.setContrast((byte) 0);
//            pictureInfo.setBrightness((byte) 0);
            pictureInfo.setEffect(PictureEffect.RealPicture);

            ShapeComponentNormal sc = (ShapeComponentNormal) controlPicture.getShapeComponent();
            sc.setOffsetX(0);
            sc.setOffsetY(0);
            sc.setGroupingCount(0);
            sc.setLocalFileVersion(1);
            sc.setWidthAtCreate(fromMM(shapePosition.width));
            sc.setHeightAtCreate(fromMM(shapePosition.height));
            sc.setWidthAtCurrent(fromMM(shapePosition.width));
            sc.setHeightAtCurrent(fromMM(shapePosition.height));
            sc.setRotateAngle(0);
            sc.setRotateXCenter(fromMM(shapePosition.width / 2));
            sc.setRotateYCenter(fromMM(shapePosition.height / 2));

            sc.createLineInfo();
            LineInfo li = sc.getLineInfo();
            li.getProperty().setLineEndShape(LineEndShape.Flat);
            li.getProperty().setStartArrowShape(LineArrowShape.None);
            li.getProperty().setStartArrowSize(LineArrowSize.MiddleMiddle);
            li.getProperty().setEndArrowShape(LineArrowShape.None);
            li.getProperty().setEndArrowSize(LineArrowSize.MiddleMiddle);
            ;
            li.getProperty().setFillStartArrow(true);
            li.getProperty().setFillEndArrow(true);
            li.getProperty().setLineType(LineType.None);
            li.setOutlineStyle(OutlineStyle.Normal);
            li.setThickness(0);
            li.getColor().setValue(0);

//            sc.createFillInfo();
//            FillInfo fi = sc.getFillInfo();
//            fi.getType().setPatternFill(false);
//            fi.getType().setImageFill(true);
//            fi.getType().setGradientFill(false);
//            fi.createImageFill();
//            ImageFill imgF = fi.getImageFill();
//            imgF.setImageFillType(ImageFillType.FitSize);
//            imgF.getPictureInfo().setBrightness((byte) 0);
//            imgF.getPictureInfo().setContrast((byte) 0);
//            imgF.getPictureInfo().setEffect(PictureEffect.RealPicture);
//            imgF.getPictureInfo().setBinItemID(binDataID);

            sc.createShadowInfo();
            ShadowInfo si = sc.getShadowInfo();
            si.setType(ShadowType.None);
            si.getColor().setValue(0xc4c4c4);
            si.setOffsetX(0);
            si.setOffsetY(0);
            si.setTransparnet((short) 0);

            sc.setMatrixsNormal();

            scp.setImageHeight(fromMM(shapePosition.height));
            scp.setImageWidth(fromMM(shapePosition.width));
            scp.setInstanceId(0x5bb810e1);

            scp.setTopAfterCutting(0);
            scp.setLeftAfterCutting(0);
            scp.setBottomAfterCutting(0);
            scp.setRightAfterCutting(0);


//            setCtrlHeaderGso(rectangle.getHeader(), shapePosition);
//            setShapeComponent((ShapeComponentNormal) rectangle.getShapeComponent(), shapePosition,binDataID);
//            setShapeComponentRectangle(rectangle.getShapeComponentRectangle(), shapePosition);

            String writePath = "sample_hwp\\test-write-image.hwp";
            HWPWriter.toFile(hwpFile, writePath);
            System.out.println("done");
        }
    }

    private static int addBinDataInDocInfo(HWPFile file, int streamIndex) {
        BinData bd = new BinData();
        bd.getProperty().setType(BinDataType.Embedding);
        bd.getProperty().setCompress(BinDataCompress.ByStroageDefault);
        bd.getProperty().setState(BinDataState.NotAcceess);
        bd.setBinDataID(streamIndex);
        bd.setExtensionForEmbedding("jpg");
        file.getDocInfo().getBinDataList().add(bd);
        return file.getDocInfo().getBinDataList().size();
    }

    private static String getStreamName(int streamIndex, String imageFileExt) {
        return "Bin" + String.format("%04X", streamIndex) + "." + imageFileExt;
    }

    private static byte[] loadFile() throws IOException {
        File file = new File("sample_hwp\\sample.jpg");
        byte[] buffer = new byte[(int) file.length()];
        InputStream ios = null;
        try {
            ios = new FileInputStream(file);
            IOUtils.readFully(ios, buffer);
        } finally {
            try {
                if (ios != null) {
                    ios.close();
                }
            } catch (IOException e) {
            }
        }
        return buffer;
    }

    private static int fromMM(int mm) {
        if (mm == 0) {
            return 1;
        }

        return (int) ((double) mm * 72000.0f / 254.0f + 0.5f);
    }
}

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

I found a mistake in the part that sets the internal coordinates of the image.

        PositionXY leftTop = scp.getLeftTop();
        PositionXY leftBottom = scp.getLeftBottom();
        PositionXY rightBottom = scp.getRightBottom();
        PositionXY rightTop = scp.getRightTop();

        leftTop.setX(0);
        leftTop.setY(0);
        rightTop.setX(fromMM(shapePosition.width));
        rightTop.setY(0);
        leftBottom.setX(0);
        leftBottom.setY(fromMM(shapePosition.height));
        rightBottom.setX(fromMM(shapePosition.width));
        rightBottom.setY(fromMM(shapePosition.height));

You need to set it like above.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

So the picture start point is left top?
I thought it was left bottom is the start point.
ok, it working. thanks very much

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

other question: how to create a new page,
i use below code.

Section secondSection = hwpFile.getBodyText().addNewSection();
Paragraph secondParagraph = secondSection.addNewParagraph();

but open .hwp will alert a error message
image

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

The addNewSection() and addNewParagraph() functions simply add a Section object or a Paragaph object without adding or setting subobjects. You have to add the appropriate subobject and set its property value. I would recommend that you make a file with the desired status (page added) in the Hangul program and read it into this library. After analyzing the file, you might want to create a file based on the analysis results.

I will provide a sample of this as soon as possible.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

great. thank you. waiting for you sample .
i try to use addNewSection() and addNewParagraph() to add new page,
when add so many property ,write out file ,open it . i just see a new paragraph not new page.

i use Hangul to create a two page .hwp file and read in library but not see any page info.
image

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

hello,maybe we can add default property for every component.
then library easy to use .

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

I am try to add so many text and table to file, i found the page added auto.

so, it's mean the '.hwp' no page info . just have section and section' paragraph
and many property.

the page size is compute result is dynamic.

Can i understand like that?

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

ok.i got how to create a new page.
just set

Paragraph secondParagraph = firstSection.addNewParagraph();
secondParagraph.getHeader().getDivideSort().setDividePage(true);

then the paragraph will go to the new page.

other i try to use Hangul to edit the file,add some text to the secondParagraph save the file.
when use library open i found the file just one paragraph.

and

paragraph.getHeader().getDivideSort().isDividePage()//return false
paragraph.getHeader().getDivideSort().isDivideColumn//return true 
paragraph.getHeader().getDivideSort().getValue()// return 3

ok,it funny .
i am continue research

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

You are very nice, doing well....

Word processors such as Hangul generally do not divide the page into file formats.
The word processor fills empty pages with paragraphs, and creates a new page if there is not enough space to fill the next paragraph. Thus, There is no Page Object in file format.

So, what is the section?
A Section is a part that semantically divides a document. For example, If the document is divided into three chapter, the Hangul file that stores the document May have three section objects. This is related to building the structure of the document. And sections can reset page properties such as page size and progress direction. If you want to output part of the document in a different page format, you need to add a section, and the section should set the page property. Generally, word processors such as Hangul or MS Word support this function. Please, refer to MS Word's manual

Paragraph's function that called "Divide Option" is useful for arbitrarily adding pages without adding sections. I also use this feature when creating a new page.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

thank you for you response.
it you mean create a new page just add a new paragraph not need more section?
add new section only when we need different page format?

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

Yes, what you think is right. I know...

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

Hi,can you tell me how to set the table cell background color or image?
thank you.

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

The property representing the background of the table cell is not in the cell.
These are in a BorderFill object (in DocInfo) connected to the cell.

Please. see my example code(kr.dogfoot.hwplib.test.TestMakingTable)

There is code to set the BorderFill for the cell in the getBorderFillIDForCell () function and set the BorderFill's ID in the Cell. Setting the BorderFill object to a background color, image, etc., is similar to the way for ShapeComponentPicture Object.

Try it.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

could you tell me ,how to set the text color ,size, under line, in paragraph?

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

The property representing the text color ,size, under line is setted with CharShape object which is in DocInfo.

Create a new CharShape object and set its properties. Then you need to set the index of the CharShape in the paragraph.This is handled by the ParaCharShape object. Create ParaCharShape Object in Paragraph using createCharShape().

Get ParaCharShape object using getCharShape(), Then call addParaCharShape() to set the index of the CharShape.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

can you write a sample ,this is so complex.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

image

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

Ok. I will write sample code within this week.

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

Show sample code(TestMakingCharShape.java). I hope this helps

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

woo, it every useful.
let me try it .

thank you.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

first question :

what is Batang ?

second question:
i don't understand why need create many FaceName and they just a empty object FaceName fn = new FaceName(); ?
i think the sample_hwp\test-blank.hwp maybe has contain them.

private int createFaceNameForBatang() {
		FaceName fn;

		// 한글 부분을 위한 FaceName 객체를 생성한다. (create FaceName Object for hangul part.)
		fn = hwpFile.getDocInfo().addNewHangulFaceName();
		setFaceNameForBatang(fn);

		// 영어 부분을 위한 FaceName 객체를 생성한다. (create FaceName Object for english part.)
		fn = hwpFile.getDocInfo().addNewEnglishFaceName();
		setFaceNameForBatang(fn);

		// 한자 부분을 위한 FaceName 객체를 생성한다. (create FaceName Object for hanja(Chinese)
		// part.)
		fn = hwpFile.getDocInfo().addNewHanjaFaceName();
		setFaceNameForBatang(fn);

		// 일본어 부분을 위한 FaceName 객체를 생성한다.(create FaceName Object for japanse part.)
		fn = hwpFile.getDocInfo().addNewJapaneseFaceName();
		setFaceNameForBatang(fn);

		// 기타 문자 부분을 위한 FaceName 객체를 생성한다.(create FaceName Object for etc part.)
		fn = hwpFile.getDocInfo().addNewEtcFaceName();
		setFaceNameForBatang(fn);

		// 기호 문자 부분을 위한 FaceName 객체를 생성한다.(create FaceName Object for symbol part.)
		fn = hwpFile.getDocInfo().addNewSymbolFaceName();
		setFaceNameForBatang(fn);

		// 사용자 정의 문자 부분을 위한 FaceName 객체를 생성한다.(create FaceName Object for user part.)
		fn = hwpFile.getDocInfo().addNewUserFaceName();
		setFaceNameForBatang(fn);

		return hwpFile.getDocInfo().getHangulFaceNameList().size() - 1;
	}

question 3:
if i just want to set chinese font face name use down code ok?

		CharShape cs = hwpFile.getDocInfo().addNewCharShape();
		//cs.getFaceNameIds().setForAll(faceNameIndexForBatang);// this is the all font face 
                FaceName fn = hwpFile.getDocInfo().addNewHanjaFaceName();
		String fontName = "chinese font name";
		fn.getProperty().setHasBaseFont(false);
		fn.getProperty().setHasFontInfo(false);
		fn.getProperty().setHasSubstituteFont(false);
		fn.setName(fontName);
               int faceNameId=hwpFile.getDocInfo().getHanjaFaceNameList().size();
		cs.getFaceNameIds().setHanja(faceNameId);

or

                CharShape cs = hwpFile.getDocInfo().addNewCharShape();
		// 바탕 폰트를 위한 FaceName 객체를 링크한다. (link FaceName Object for 'Batang' font.)
                String faceName='chinese font name';
		cs.getFaceNameIds().setForAll(createFaceNameForBatang(faceName));

               private int createFaceNameForBatang(String fontName){
                   FaceName fn;

		     // 한글 부분을 위한 FaceName 객체를 생성한다. (create FaceName Object for hangul part.)
		    fn = hwpFile.getDocInfo().addNewHangulFaceName();
		       setFaceNameForBatang(fn,faceName);
                      ........//other font face

		     return hwpFile.getDocInfo().getHangulFaceNameList().size() - 1;
               }
        private void setFaceNameForBatang(FaceName fn,String fontName) {
		 
		fn.getProperty().setHasBaseFont(false);
		fn.getProperty().setHasFontInfo(false);
		fn.getProperty().setHasSubstituteFont(false);
		fn.setName(fontName);
	}

thank you

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

And how to change the text align with code
image
i see the TextVerticalAlignment class but it just have Top,Center,Bottom , not have Left and Right

from hwplib.

neolord0 avatar neolord0 commented on August 23, 2024

1 what is Batang ?

  • "Batang" is a font name for korean.
  1. i don't understand why need create many FaceName and they just a empty object FaceName fn = new FaceName(); ?
  • The "Hangul" program divides the characters into seven subparts. Different fonts can be set for each part. So you have to create 7 FaceName. This is specified in the "Hangul" format. It is a little inefficient compared to other formats, but it should be followed.
  1. That picture indicate "Text Horizontal Alignment" property. It's propety is in ParaShape which located in DocInfo. In the same way as CharShape, you need to create a ParaShape and link it to a paragraph.
    Try it.

from hwplib.

zuoliang0 avatar zuoliang0 commented on August 23, 2024

ok,thanks。
I have been got how to create text align and text color .
image
This is your achivement.
thank you very much.
대단히 감사합니다.

from hwplib.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.